// screen_employees.jsx — Employees · Hiring (merged HirePage ⊕ employees: roster + hire/promote, single-plan pricing)
(function () {
  const { useState } = React;
  const h = React.createElement;
  window.Screens = window.Screens || {};
  // PC-2: full helper destructure from window — every referenced helper, no bare globals.
  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;
	const displayName = (role) => window.officeRoleName ? window.officeRoleName(role, role.id) : role.title;
	const displayMission = (role) => window.officeRoleMission ? window.officeRoleMission(role, role.id) : role.tagline;
	const taskName = (role, skill) => window.skillCopy ? window.skillCopy(role.id, skill, "name") : skill.name;

  function Employees({ ctx }) {
    const [confirm, setConfirm] = useState(null); // { kind:'hire'|'promote', role }
    const [view, setView] = useState("cards");
    const plan = ctx.office.plan;
    // shared so Cards and Table render byte-identical actions with identical RBAC gating
    const pendingHireFor = (r) => (ctx.office.inbox || []).find((it) => it.type === "hire" && it.role === r.id);
    const employeeStatus = (r) => r.hired ? (r.hired.tier === "senior" ? "hired-senior" : "hired-standard") : pendingHireFor(r) ? "hire-requested" : "hiring";
    const roleAttrs = (r) => {
      const pending = pendingHireFor(r);
      const tier = r.hired && r.hired.tier ? r.hired.tier : "";
      return {
        "data-employee-role-id": r.id,
        "data-employee-status": employeeStatus(r),
        "data-employee-hired": r.hired ? "true" : "false",
        "data-employee-tier": tier,
        "data-employee-hire-pending": pending ? "true" : "false",
        "data-employee-pending-approval-id": pending ? pending.id : "",
      };
    };
    const statusChip = (r) => r.hired
      ? h(Chip, { tone: "mint", "data-employee-status": employeeStatus(r), "data-employee-role-id": r.id }, r.hired.tier === "senior" ? "Hired · Senior" : "Hired · Standard")
      : pendingHireFor(r)
        ? h(Chip, { tone: "amber", "data-employee-status": employeeStatus(r), "data-employee-role-id": r.id }, "Hire requested")
        : h(Chip, { tone: "gray", "data-employee-status": employeeStatus(r), "data-employee-role-id": r.id }, "Hiring");
    const priceOf = (r) => "HK$" + (r.hired && r.hired.tier === "senior" ? plan.senior.toLocaleString() : plan.standard);
	    const tryFirst = (r) => h(Button, { sm: true, "data-employee-action": "try-first", "data-employee-role-id": r.id, onClick: () => ctx.openPage("training-setup", r.id) }, "Try sample");
	    const configureBtn = (r) => h(Button, { sm: true, "data-employee-action": "configure", "data-employee-role-id": r.id, onClick: () => ctx.openPage("config", r.id) }, "Set up");
    // the new star affordance: brief a hired employee (opens the per-employee briefing screen)
	    const briefBtn = (r) => r.hired ? h(Button, { sm: true, variant: "primary", icon: "message", "data-employee-action": "brief", "data-employee-role-id": r.id, onClick: () => ctx.openPage("employee", r.id) }, "Give task") : null;
    const primaryAction = (r) => {
      const pending = pendingHireFor(r);
      if (!r.hired && pending) {
        return h(Button, { variant: "primary", sm: true, iconRight: "arrowRight", "data-employee-action": "review-request", "data-employee-role-id": r.id, "data-approval-id": pending.id, onClick: () => { ctx.setHighlight(pending.id); ctx.openPage("approvals"); } }, "Review request");
      }
      return !r.hired
        ? h(Button, { variant: "primary", sm: true, disabled: !ctx.can("requestHire"), title: ctx.can("requestHire") ? "" : ctx.denyReason("requestHire"), "data-employee-action": ctx.can("hire") ? "hire" : "request-hire", "data-employee-role-id": r.id, onClick: () => setConfirm({ kind: "hire", role: r }) }, ctx.can("hire") ? "Hire" : "Request hire")
        : r.hired.tier === "standard"
          ? h(Button, { sm: true, disabled: !ctx.can("promoteL2"), title: ctx.can("promoteL2") ? "" : ctx.denyReason("promoteL2"), "data-employee-action": "promote", "data-employee-role-id": r.id, onClick: () => setConfirm({ kind: "promote", role: r }) }, "Promote to Senior")
          : null;
    };
    return h("div", { "data-employees-root": "true", "data-employees-view": view },
      h(PageHeader, { eyebrow: "Workforce", title: "Employees",
        right: h(Segmented, { value: view, onChange: setView, options: [
          { value: "cards", label: "Cards", attrs: { "data-employees-view-option": "cards", "data-employees-view-active": view === "cards" ? "true" : "false" } },
          { value: "table", label: "Table", attrs: { "data-employees-view-option": "table", "data-employees-view-active": view === "table" ? "true" : "false" } },
        ] }),
        sub: "Hire or promote AI employees. New hires are free for " + plan.trialDays + " days; hire 3 or more for 10% off." }),
      view === "cards" && h("div", { className: "skill-grid", "data-employees-list-view": "cards", "data-employees-count": String(ctx.office.roles.length) }, ctx.office.roles.map((r) => h(Card, Object.assign({ key: r.id, "data-employee-card": "true", style: { borderTop: "4px solid " + r.color, padding: 16 } }, roleAttrs(r)),
        h("div", { className: "row gap10", style: { marginBottom: 8 } },
          h(window.Face, { role: r, size: 32, variant: "portrait" }),
          h("div", { className: "grow" },
	            h("b", { style: { fontSize: 15.5 } }, displayName(r)),
	            h("div", { style: { fontSize: 12.5, color: "var(--text-faint)" } }, r.skills.length + " tasks")),
          statusChip(r)),
        h("p", { style: { fontSize: 13.5, color: "var(--text-dim)", lineHeight: 1.55, minHeight: 42 } }, displayMission(r)),
        h("div", { className: "row gap6 wrap", style: { margin: "10px 0 14px" } },
	          r.skills.slice(0, 3).map((s) => h(Chip, { key: s.id, tone: "gray" }, taskName(r, s))),
          h(Chip, { tone: "gray" }, h("span", null, "+" + (r.skills.length - 3)))),
        r.hired && r.hired.trial && h("div", { style: { margin: "0 0 14px" } },
          h(ProgressBar, { value: (r.hired.trial.day / r.hired.trial.total * 100), tone: "blue", height: 6 }),
          h("p", { style: { fontSize: 12, marginTop: 6, color: "var(--text-faint)" } },
            h("span", null, "Trial day " + r.hired.trial.day + "/" + r.hired.trial.total + " · up to 20 tasks/day · stop anytime, no charge"))),
        h("div", { className: "price-row" },
          h("div", null,
            h("span", { className: "price" }, h("span", null, "HK$" + (r.hired && r.hired.tier === "senior" ? plan.senior.toLocaleString() : plan.standard))),
            h("span", { style: { color: "var(--text-faint)" } }, "/mo")),
	          h("div", { className: "row gap8 wrap" },
	            briefBtn(r), tryFirst(r), configureBtn(r), primaryAction(r)))))),
      view === "table" && h("div", { className: "glass", "data-employees-list-view": "table", "data-employees-count": String(ctx.office.roles.length), style: { overflow: "hidden", marginBottom: 18 } },
        h("div", { style: { overflowX: "auto" } },
          h("table", { className: "tbl", "data-employees-table": "true" },
	            h("thead", null, h("tr", null, ["Employee", "Status", "Tasks", "Price/mo", ""].map((cH, i) => h("th", { key: i, style: i === 4 ? { textAlign: "right" } : (i === 2 || i === 3) ? { textAlign: "right" } : null }, cH)))),
            h("tbody", null, ctx.office.roles.map((r) => h("tr", Object.assign({ key: r.id, "data-employee-row": "true" }, roleAttrs(r)),
              h("td", null, h("div", { className: "row gap10" }, h(window.Face, { role: r, size: 28, variant: "head" }),
                h("div", { style: { minWidth: 0 } },
	                  h("b", { style: { fontSize: 13.5 } }, h("span", null, displayName(r))),
                  h("div", { style: { fontSize: 12, color: "var(--text-faint)", maxWidth: 380, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, h("span", null, displayMission(r)))))),
              h("td", null, statusChip(r)),
              h("td", { className: "mono", style: { textAlign: "right" } }, "" + r.skills.length),
              h("td", { style: { textAlign: "right", whiteSpace: "nowrap" } }, h("span", { className: "price" }, h("span", null, priceOf(r))), h("span", { style: { color: "var(--text-faint)" } }, "/mo")),
	              h("td", { style: { textAlign: "right" } }, h("div", { className: "row gap8 wrap", style: { justifyContent: "flex-end" } }, briefBtn(r), tryFirst(r), configureBtn(r), primaryAction(r))))))))),
      h("div", { className: "rule-banner", style: { marginTop: 18 } },
	        h("span", null, "Senior employees can request low-risk repeat work. Standard employees always need approval.")),
      confirm && (function () {
        const requestOnly = confirm.kind === "hire" && !ctx.can("hire");
        // C11-iii: split role.title into its own <span> so the 繁中 data reverse-maps independently
        // and the surrounding English literals match their own dict keys.
        const title = confirm.kind !== "hire"
	          ? h("span", null, h("span", null, "Promote "), h("span", null, displayName(confirm.role)), h("span", null, " to Senior"))
          : requestOnly
	            ? h("span", null, h("span", null, "Request hire · "), h("span", null, displayName(confirm.role)))
	            : h("span", null, h("span", null, "Hire "), h("span", null, displayName(confirm.role)));
        const modalKind = confirm.kind === "hire" ? (requestOnly ? "request-hire" : "hire") : "promote";
        return h(Modal, {
          "data-employee-modal": modalKind,
          "data-employee-role-id": confirm.role.id,
          title: title,
	          sub: confirm.kind !== "hire" ? "Starts now. The monthly fee changes from HK$990 to HK$2,480."
	            : requestOnly ? "The owner will review this hire request."
	            : "First 14 days free, up to 20 tasks a day.",
          width: 540, onClose: () => setConfirm(null),
          footer: [
	            h(Button, { key: "c", "data-employee-action": "modal-cancel", "data-employee-role-id": confirm.role.id, onClick: () => setConfirm(null) }, "Cancel"),
            h(Button, { key: "ok", variant: "primary", "data-employee-action": confirm.kind !== "hire" ? "confirm-promote" : requestOnly ? "submit-hire-request" : "confirm-hire", "data-employee-role-id": confirm.role.id, onClick: () => {
              if (confirm.kind === "hire") {
                // Double-toast fix: ctx.requestHire already toasts ("Hire request submitted to the owner for approval"),
                // so the request branch does NOT add its own toast. ctx.hire/ctx.promote do not self-toast.
                if (requestOnly) ctx.requestHire(confirm.role.id);
	                else { ctx.hire(confirm.role.id); ctx.showToast(displayName(confirm.role) + " added"); }
	              } else { ctx.promote(confirm.role.id); ctx.showToast(displayName(confirm.role) + " promoted to Senior"); }
              setConfirm(null);
            } }, confirm.kind !== "hire" ? "Confirm promotion" : requestOnly ? "Submit request" : "Confirm hire (14 days free)"),
          ],
        },
          confirm.kind === "hire"
            ? h("ul", { className: "ben" },
	                h("li", null, "All tasks are available today"),
	                h("li", null, "Every draft goes to My Desk first"),
                h("li", null, "Stop anytime during the trial, no charge"))
            : h("ul", { className: "ben" },
	                h("li", null, "Can use approved company files"),
	                h("li", null, "Can request low-risk repeat work"),
	                h("li", null, "All work stays in history")));
      })());
  }

  window.Screens.employees = Employees;

	  // ---- Per-employee briefing screen (#employee/<roleId>) — the single place you brief an employee.
	  const skillNameOf = (role, id) => { const s = (role.skills || []).find((x) => x.id === id); return (s && taskName(role, s)) || id; };
	  function parseEmployeeArg(arg) {
	    const parts = String(arg || "").split("~");
	    return { roleId: parts[0] || "", intentId: parts[1] || null };
	  }
	  function employeeRouteArg(roleId, intentId) {
	    return String(roleId || "") + (intentId ? "~" + intentId : "");
	  }

	  // Drafting reveal — sample work is always handed to My Desk.
  function BriefReveal({ ctx, role, intent, onClose }) {
    const [step, setStep] = React.useState(0);
    const steps = ["Reading 《" + intent.file + "》", "Drafting from the source", "Checking the claim against the file", "Ready for your review"];
    React.useEffect(() => { if (step < steps.length) { const t = setTimeout(() => setStep((s) => s + 1), 650); return () => clearTimeout(t); } }, [step]);
    const done = step >= steps.length;
    return h(Modal, { title: h("span", null, h("span", null, "Drafting · "), h("span", null, displayName(role))),
      sub: "Demo — shows a sample draft built from your example files.", icon: "stamp", width: 640, onClose,
      footer: [
        h(Button, { key: "c", "data-employee-action": "brief-reveal-cancel", "data-employee-role-id": role.id, "data-employee-action-intent-id": intent.intentId, onClick: onClose }, "Cancel"),
        // briefreveal-no-skip: action is NOT gated on the cosmetic reveal — draft content is pre-authored (intent.draftLines), so let the user send immediately. The honest "Demo — sample draft" sub stays in the Modal header.
        h(Button, { key: "s", variant: "primary", icon: "stamp", disabled: !!role.paused, title: role.paused ? "Resume this employee before giving a new task." : "", "data-employee-action": "send-brief-approval", "data-employee-role-id": role.id, "data-employee-action-intent-id": intent.intentId, onClick: () => { ctx.confirmBrief(role.id, intent.intentId); onClose(); } }, "Send to My Desk"),
      ] },
      // The file name stays verbatim user data; the surrounding label is localized.
      h("div", { style: { padding: "4px 2px" } },
        steps.map((s, i) => (i <= step) && h("div", { key: i, className: "fade-line row gap8", style: { padding: "6px 0", fontSize: 13 } },
          h(InlineIcon, { name: (i < step || done) ? "check" : "clock" }), h("span", null, s))),
        done && h("div", { className: "draft", style: { marginTop: 12 } },
          (intent.draftLines || []).map((l, i) => h("p", { key: i }, l)),
          h("p", { style: { color: "var(--text-faint)", marginTop: 6 } }, "File used: 《" + intent.file + "》")),
	        done && h("p", { style: { fontSize: 12.5, color: "var(--text-dim)", marginTop: 10 } }, "The draft goes to My Desk for approval.")));
  }

  // Governed conversation — open text + intent-match + graceful deflect; every confirm routes through BriefReveal -> the desk.
  function EmployeeConversation({ ctx, role, onBrief }) {
    const [text, setText] = React.useState("");
    const [openRunId, setOpenRunId] = React.useState(null);
    const thread = (ctx.office.threads && ctx.office.threads[role.id]) || [];
    const intents = (ctx.office.briefLibrary && ctx.office.briefLibrary[role.id]) || [];
    const findIntent = (id) => intents.find((x) => x.intentId === id);
    const findRun = (id) => (ctx.office.runs || []).find((r) => r.id === id);
    function send(v, intentId) { const t = (v != null ? v : text).trim(); if (!t || role.paused) return; ctx.sendBrief(role.id, t, intentId ? { intentId: intentId } : undefined); setText(""); }
    // agent bubbles render from structured fields via dict-backed English-source fragments (localizes in 繁/简);
    // file/skill/summary are 繁中 data passed through verbatim. user messages render their raw text.
    // INTENTIONAL: the verbatim 繁中 named-source data (《file》 citations, skill names, 高/中/低, 引用：檔案室, 剛剛) is the grounding convention, consistent across the product + the spec red line — NOT an i18n miss. Do not translate or English-ify it.
    const bodyOf = (m) => {
      if (m.kind === "confirm-ask") return "I'll draft this from 《" + m.file + "》 for " + m.skill + ". Draft it?";
      if (m.kind === "deflect") return "I cannot do that task. I can help with " + m.summary + ". I only work from your files, so I won't guess.";
	      if (m.kind === "draft-created") return h("span", null, "Draft ready in My Desk.");
      return m.text; // user message (verbatim)
    };
    const bubble = (m) => {
      const mine = m.from === "user";
      return h("div", { key: m.id, "data-employee-message": m.id || "", "data-employee-message-from": m.from || "", "data-employee-message-kind": m.kind || "", "data-employee-message-intent-id": m.intentId || "", "data-approval-id": m.inboxId || "", "data-run-id": m.runId || "", "data-employee-handoff-role-id": m.handoffTo || "", style: { display: "flex", justifyContent: mine ? "flex-end" : "flex-start", marginBottom: 10 } },
        h("div", { style: { maxWidth: "80%", padding: "9px 12px", borderRadius: 12, fontSize: 13, lineHeight: 1.5,
          background: mine ? "var(--blue)" : "var(--bg-3)", color: mine ? "#fff" : "var(--text)", border: mine ? "none" : "1px solid var(--border)" } },
          h("div", null, bodyOf(m)),
          m.kind === "confirm-ask" && h("div", { style: { marginTop: 8 } },
            h(Button, { sm: true, variant: "primary", icon: "stamp", disabled: !!role.paused, title: role.paused ? "Resume this employee before giving a new task." : "", "data-employee-action": "confirm-draft", "data-employee-role-id": role.id, "data-employee-action-intent-id": m.intentId || "", onClick: () => { const it = findIntent(m.intentId); if (it) onBrief(it); } }, "Draft it")),
          m.kind === "deflect" && m.handoffTo && h("div", { style: { marginTop: 8 } },
            h(Button, { sm: true, "data-employee-action": "handoff-colleague", "data-employee-role-id": role.id, "data-employee-handoff-role-id": m.handoffTo || "", onClick: () => ctx.openPage("employee", m.handoffTo) }, h("span", null, "Bring in "), h("span", null, (ctx.office.roleById[m.handoffTo] || {}).title || "a colleague"))),
          m.kind === "draft-created" && h("div", { style: { marginTop: 8, display: "grid", gap: 8 } },
            h("div", { className: "row gap6 wrap" },
	              h(Button, { sm: true, iconRight: "arrowRight", "data-employee-action": "open-approval-desk", "data-employee-role-id": role.id, "data-approval-id": m.inboxId || "", "data-run-id": m.runId || "", onClick: () => { if (ctx.setHighlight && m.inboxId) ctx.setHighlight(m.inboxId); ctx.openPage("approvals"); } }, "Open in My Desk"),
	              m.runId && h("button", { type: "button", className: "ac-chip", "data-employee-action": "toggle-run-trace", "data-employee-role-id": role.id, "data-run-id": m.runId || "", onClick: () => setOpenRunId(openRunId === m.runId ? null : m.runId), "aria-expanded": openRunId === m.runId ? "true" : "false", "aria-label": (openRunId === m.runId ? "Hide work history " : "View work history ") + m.runId },
	                openRunId === m.runId ? "Hide history" : "View history")),
            openRunId === m.runId && findRun(m.runId) && h(window.RunTrace, { run: findRun(m.runId),
              onOpenSource: (src) => { if (ctx.setHighlight && src && src.fileId) ctx.setHighlight(src.fileId); ctx.openPage("files", src && src.fileId); },
              onOpenInbox: (id) => { if (ctx.setHighlight && id) ctx.setHighlight(id); ctx.openPage("approvals"); } }))));
    };
    return h(Card, { "data-employee-conversation": "true", "data-employee-role-id": role.id, style: { padding: 16, display: "flex", flexDirection: "column" } },
      h("div", { style: { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", color: "var(--text-faint)", marginBottom: 12 } }, "CONVERSATION"),
      h("div", { "data-employee-thread": "true", "data-employee-role-id": role.id, style: { minHeight: 200, maxHeight: 360, overflowY: "auto", marginBottom: 12 } },
        thread.length ? thread.map(bubble)
	          : h(EmptyHint, null, "Give " + displayName(role) + " a task. Drafts use your files and wait in My Desk.")),
      // skill-name chips: labels are verbatim 繁中 skill names — intentional named-source grounding (consistent across the product + spec red line), NOT an i18n miss. Do not translate.
      intents.length > 0 && h("div", { className: "row gap6 wrap", style: { marginBottom: 10 } },
        intents.map((it) => h("button", { key: it.intentId, className: "chip", disabled: !!role.paused, title: role.paused ? "Resume this employee before giving a new task." : "", "data-employee-action": "send-intent-brief", "data-employee-role-id": role.id, "data-employee-conversation-intent-id": it.intentId, style: { cursor: role.paused ? "not-allowed" : "pointer", border: "1px solid var(--border)", background: "var(--bg-2)" },
          onClick: () => send(skillNameOf(role, it.skillId), it.intentId) }, skillNameOf(role, it.skillId)))),
      h("div", { className: "row gap8", style: { alignItems: "flex-end" } },
	      h("textarea", { className: "field", rows: 2, value: text, disabled: !!role.paused, "aria-label": "Give this employee a task", "data-employee-field": "brief-text", "data-employee-role-id": role.id, placeholder: role.paused ? "Resume this employee before giving a new task." : "e.g. draft a reply about the refund window", style: { flex: 1, resize: "none" },
          onChange: (ev) => setText(ev.target.value), onKeyDown: (ev) => { if (ev.key === "Enter" && !ev.shiftKey) { ev.preventDefault(); send(); } } }),
        h("div", { style: { display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 } },
          h(Button, { variant: "primary", icon: "send", disabled: !!role.paused || !text.trim(), title: role.paused ? "Resume this employee before giving a new task." : "", "data-employee-action": "send-brief", "data-employee-role-id": role.id, onClick: () => send() }, "Send"),
          h("span", { style: { fontSize: 11, color: "var(--text-faint)", whiteSpace: "nowrap" } }, "Enter to send · Shift+Enter for newline"))));
  }

  // Express composer — pick an intent (skill + named file); converges on the same confirm/draft path. No free-text injection.
  // INTENTIONAL: the skill-name tab labels and the 《file》 source line below render verbatim 繁中 named-source data — the grounding convention (consistent across the product + spec red line), NOT an i18n miss. Do not translate.
	  function EmployeeComposer({ ctx, role, routeIntentId, onSelectIntent, onBrief }) {
	    const intents = (ctx.office.briefLibrary && ctx.office.briefLibrary[role.id]) || [];
	    const firstIntentId = intents[0] ? intents[0].intentId : null;
	    const routedIntent = routeIntentId && intents.find((x) => x.intentId === routeIntentId);
	    const [sel, setSel] = React.useState(routedIntent ? routedIntent.intentId : firstIntentId);
	    React.useEffect(() => {
	      const next = (routeIntentId && intents.find((x) => x.intentId === routeIntentId)) ? routeIntentId : firstIntentId;
	      setSel(next || null);
	    }, [role.id, routeIntentId, firstIntentId, intents.length]);
	    if (!intents.length) return h(Card, { style: { padding: 16 } },
	      h("div", { style: { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", color: "var(--text-faint)", marginBottom: 10 } }, "QUICK BRIEF"),
	      h(EmptyHint, null, "No quick-brief tasks set up yet — type a task in the conversation instead."));
	    const cur = intents.find((x) => x.intentId === sel) || intents[0];
	    function selectIntent(intentId) {
	      if (!intents.some((x) => x.intentId === intentId)) return;
	      setSel(intentId);
	      if (onSelectIntent) onSelectIntent(intentId);
	    }
	    return h(Card, { style: { padding: 16 } },
	      h("div", { style: { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", color: "var(--text-faint)", marginBottom: 12 } }, "QUICK BRIEF"),
	      h("div", { className: "row gap6 wrap", style: { marginBottom: 12 } },
	        intents.map((it) => h("button", { key: it.intentId, "data-employee-intent-id": it.intentId, onClick: () => selectIntent(it.intentId),
	          className: "role-tab" + (it.intentId === sel ? " on" : ""), style: { fontSize: 12.5 } }, skillNameOf(role, it.skillId)))),
	      h("div", { "data-employee-brief-current": cur.intentId, style: { fontSize: 12.5, color: "var(--text-dim)", marginBottom: 12 } },
	        h("span", null, "File: "), h("b", null, "《" + cur.file + "》")),
	      h(Button, { variant: "primary", icon: "stamp", disabled: !!role.paused, title: role.paused ? "Resume this employee before giving a new task." : "", "data-employee-action": "open-brief-reveal", "data-employee-role-id": role.id, "data-employee-action-intent-id": cur.intentId, onClick: () => onBrief(cur) }, "Draft it"));
	  }

	  function EmployeeScreen({ ctx }) {
	    const route = parseEmployeeArg(ctx.pageArg);
	    const roleId = route.roleId;
	    const role = roleId && ctx.office.roleById[roleId];
    // invalid roleId -> bounce to the roster (navHas only validates the screen segment, not the arg)
    React.useEffect(() => { if (!role) ctx.openPage("employees", null); }, [roleId]);
    const [reveal, setReveal] = React.useState(null);
    if (!role) return null;
    const files = (ctx.office.files || []).filter((f) => (f.usedBy || []).indexOf(roleId) >= 0);
    const hired = !!role.hired;
    const enabledSkills = role.skills.filter((s) => s.enabled);
    // Run Trace: how this employee starts work (visible triggers) + its recent runs (non-empty history)
    const triggers = [];
    role.skills.filter((s) => s.enabled && s.routine).forEach((s) => triggers.push({ icon: "clock", label: "On a schedule", detail: s.routine }));
    if ((role.connectors || []).indexOf("email") >= 0) triggers.push({ icon: "mail", label: "On a new message", detail: "Incoming emails are sorted and drafted. Every reply waits in My Desk." });
    triggers.push({ icon: "user", label: "When you delegate", detail: "Starts when you give a task below." });
    const triggersCard = h(Card, { style: { padding: 16 } },
      h("div", { style: { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", color: "var(--text-faint)", marginBottom: 4 } }, "How this employee starts work"),
      h("p", { style: { fontSize: 11.5, color: "var(--text-faint)", margin: "0 0 10px", lineHeight: 1.5 } }, "It runs these parts on its own — every result still waits on your desk."),
      triggers.map((t, i) => h("div", { key: i, className: "row gap8", style: { padding: "6px 0", alignItems: "flex-start" } },
        h("span", { style: { color: "var(--blue)", marginTop: 1, flex: "none" } }, h(window.Icon, { name: t.icon, size: 15 })),
        h("div", { style: { fontSize: 12.5, minWidth: 0 } }, h("div", { style: { fontWeight: 600 } }, t.label),
          h("div", { style: { fontSize: 12, color: "var(--text-faint)" } }, t.detail)))));
    const myRuns = (ctx.office.runs || []).filter((r) => r.roleId === roleId);
    const recentRunsCard = h(Card, { style: { padding: 16 } },
	      h("div", { style: { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", color: "var(--text-faint)", marginBottom: 12 } }, "Recent work"),
      myRuns.length
        ? h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
            myRuns.slice(0, 5).map((r) => h(window.RunTrace, { key: r.id, run: r, compact: true,
              onOpenSource: (src) => { if (ctx.setHighlight && src && src.fileId) ctx.setHighlight(src.fileId); ctx.openPage("files", src && src.fileId); },
              onOpenInbox: (iid) => { if (ctx.setHighlight) ctx.setHighlight(iid); ctx.openPage("approvals"); } })))
	        : h(EmptyHint, null, "No work yet — give this employee a task."));
    return h("div", null,
	      h(PageHeader, { eyebrow: "Employees",
	        title: h("span", null, h("span", null, "Give a task"), " · ", h("span", null, displayName(role))),
        sub: "Give this employee a plain task. It drafts from your files and sends drafts to My Desk.",
	        right: [
	          h(Button, { key: "back", sm: true, variant: "ghost", onClick: () => ctx.openPage("employees") }, "All employees"),
	        ].filter(Boolean) }),
      h("div", { className: "employee-grid", style: { display: "grid", gridTemplateColumns: "300px 1fr", gap: 16, alignItems: "start" } },
        // zone 1 — profile + scope
        h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
          h(Card, { style: { padding: 16, borderTop: "4px solid " + role.color } },
            h("div", { className: "row gap10", style: { marginBottom: 10 } }, h(window.Face, { role: role, size: 34, variant: "portrait" }),
	              h("div", { className: "grow" }, h("b", { style: { fontSize: 15.5 } }, displayName(role)),
                h("div", { style: { fontSize: 12, color: "var(--text-faint)" } }, hired ? (role.hired.tier === "senior" ? "Hired · Senior" : "Hired · Standard") : "Not hired"))),
            h("p", { style: { fontSize: 13, color: "var(--text-dim)", lineHeight: 1.55, margin: 0 } }, displayMission(role))),
          h(Card, { style: { padding: 16 } },
            h("div", { style: { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", color: "var(--text-faint)", marginBottom: 10 } }, "WORKS FROM THESE FILES"),
            files.length
              ? files.map((f) => h("div", { key: f.name, className: "row gap8", style: { padding: "6px 0", fontSize: 12.5 } }, h(InlineIcon, { name: "file" }), h("span", { className: "grow" }, f.name)))
	              : h(EmptyHint, null, "No files added yet."),
	            h("div", { style: { marginTop: 10 } }, h(Button, { sm: true, variant: "ghost", iconRight: "arrowRight", onClick: () => ctx.openPage("files") }, "Open Files"))),
          h(Card, { style: { padding: 16 } },
	            h("div", { style: { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", color: "var(--text-faint)", marginBottom: 10 } }, "TASKS"),
	            enabledSkills.slice(0, 6).map((s) => h("div", { key: s.id, className: "row gap8", style: { padding: "5px 0", fontSize: 12.5 } }, h(InlineIcon, { name: "check" }), h("span", { className: "grow" }, taskName(role, s))))),
          triggersCard),
        // zone 2 — governed conversation + express composer
        h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
          hired
            ? h(React.Fragment, null,
                recentRunsCard,
                h(EmployeeConversation, { ctx, role, onBrief: setReveal }),
	                h(EmployeeComposer, { ctx, role, routeIntentId: route.intentId, onSelectIntent: (intentId) => ctx.openPage("employee", employeeRouteArg(role.id, intentId)), onBrief: setReveal }))
            : h(Card, { style: { padding: 24, textAlign: "center" } },
	                h(EmptyHint, null, "Hire " + displayName(role) + " to give tasks."),
                h("div", { style: { marginTop: 12 } }, h(Button, { variant: "primary", onClick: () => ctx.openPage("employees") }, "Go to hiring"))))),
      reveal && h(BriefReveal, { ctx, role, intent: reveal, onClose: () => setReveal(null) }));
  }
  window.Screens.employee = EmployeeScreen;
})();
