// office-helpers.jsx — shared office helpers re-implemented in dashboard JSX,
// rendering via window.Icon. Exposed on window; Phases 4-7 CONSUME, never redefine.
(function () {
  const h = React.createElement;
  const Icon = window.Icon;

  // role glyphs (office ROLE_ICONS, canonical office ids — C4, PC-9: no ops role here)
  const ROLE_ICONS = { clerk: "file", cs: "message", sales: "chart", social: "message", acct: "dollar" };

  // English-source display copy for seeded OFFICE values. These helpers deliberately
  // map only known product copy: published profile text, filenames, snippets and other
  // user/scenario values pass through unchanged.
  const OFFICE_ROLE_NAME_EN = {
    clerk: "Admin Assistant",
    cs: "Customer Support Assistant",
    sales: "Sales Assistant",
    social: "Marketing Assistant",
    acct: "Accounting Assistant",
  };
  const OFFICE_ROLE_MISSION_EN = {
    clerk: "Summarize approved files, list next steps, and flag missing facts.",
    cs: "Draft replies from approved files. Do not answer without a source.",
    sales: "Draft quotes and follow-ups from approved prices and terms. Flag missing details.",
    social: "Draft posts from the content calendar and product file. Wait for approval.",
    acct: "Read receipts and invoices. Flag items for review. Do not post entries.",
  };
  const OFFICE_ROLE_SEED_NAME_EN = {
    "行政助理": "Admin Assistant", "行政": "Admin Assistant",
    "客服助理": "Customer Support Assistant", "客服": "Customer Support Assistant",
    "銷售助理": "Sales Assistant", "銷售": "Sales Assistant",
    "營銷助理": "Marketing Assistant", "營銷": "Marketing Assistant",
    "會計助理": "Accounting Assistant", "會計": "Accounting Assistant",
  };
  const OFFICE_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 assigned",
    "移除來源": "File removed", "上傳檔案": "File added", "歸檔檔案": "File saved", "發布設定": "Settings applied", "還原設定": "Settings undone",
    "匯出": "Downloaded", "連接器連線": "App connected", "重新授權": "App reconnected", "中斷連接": "App disconnected", "健康檢查": "Connection checked",
    "整合需求": "App requested", "更新設定": "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 RUN_TRIGGER_EN = {
    "收到新工作": "New work received",
    "夜間排程": "Overnight schedule",
    "收到新郵件": "New email received",
    "你委派": "Delegated by you",
    "每週一 09:00 · 整理上週銷售數據": "Every Monday 09:00 · Put last week's sales data in a table",
    "每週一 09:30 · 成效週報": "Every Monday 09:30 · Performance report",
  };
  const RUN_TASK_EN = {
    "訂單狀態查詢回覆": "Reply with an order update",
    "資料整理入表": "Put information in a table",
  };
  const RUN_CAVEAT_EN = {
    "示範 · 全部資料虛構": "Sample data · all fictional",
    "郵件發出後無法收回——緩衝期是最後的撤回機會": "Email cannot be recalled after sending · undo is available only during the wait",
    "等級 2 · 低風險 · 10 分鐘緩衝": "Low-risk repeat work · 10-minute undo",
    "內部表格——可隨時還原": "Internal table · can be restored anytime",
    "內部表格 · 可隨時還原": "Internal table · can be restored anytime",
    "內部報表 · 自動生成": "Internal report · created automatically",
  };
  const OFFICE_SOURCE_EN = {
    "輸入內容": "Input",
    "等級 2 · 低風險規則": "Low-risk repeat-work rule",
    "等級 2 · 低風險類別 · 依規則進入 10 分鐘緩衝": "Low-risk repeat work · 10-minute undo",
    "收發室轉入郵件 · 分類：物流／包裝 · 嚴重度：中": "Email from Apps · Category: Logistics / packaging · Priority: Medium",
    "客服轉入的個案摘要（ap7）": "Customer Support case summary (ap7)",
    "收發室轉入郵件｜依據：訂單表（今早 06:00 同步）": "Email from Apps | Based on: order sheet (synced 06:00 this morning)",
    "收發室郵件＋Drive《銷售紀錄》資料夾": "Email from Apps + Drive folder 《銷售紀錄》",
    "Instagram 成效數據（過去 7 天）": "Instagram performance data (past 7 days)",
    "Google Drive 應用程式": "Google Drive app",
    "Instagram 應用程式": "Instagram app",
    "Email 應用程式": "Email app",
    "Google Drive 同步": "Google Drive sync",
    "我的辦公桌 · 任務派發": "My Desk · task routing",
    "推送頻道正常 · 今早 09:41 最後一次同步": "Push channel healthy · last sync 09:41 this morning",
    "昨天 19:00 開箱影片發佈失敗；19:04 重試成功。今日額度 8/100": "Unboxing video failed to publish yesterday at 19:00; retry succeeded at 19:04. Today's quota: 8/100",
    "存取權於 Google 帳戶安全設定被移除 → 同步暫停（最後成功 昨天 21:14）；需重新授權": "Access was removed in Google account security settings → sync paused (last success yesterday 21:14); reconnect needed",
    "草稿照常派至客服和行政助理，回覆發出前必須批准": "Drafts are routing normally to Customer Support and Admin; replies still need approval before sending",
  };

  function cleanDisplayText(value) { return String(value == null ? "" : value).trim(); }
  function officeRoleName(role, id) {
    const roleId = id || (role && role.id) || "";
    const published = role && role.publishedProfile && typeof role.publishedProfile === "object" ? role.publishedProfile : {};
    const publishedName = cleanDisplayText(published.name);
    if (publishedName) return publishedName;
    return OFFICE_ROLE_NAME_EN[roleId]
      || OFFICE_ROLE_SEED_NAME_EN[cleanDisplayText(role && role.title)]
      || OFFICE_ROLE_SEED_NAME_EN[cleanDisplayText(role && role.short)]
      || cleanDisplayText(role && (role.title || role.short))
      || roleId
      || "Employee";
  }
  function officeRoleMission(role, id) {
    const roleId = id || (role && role.id) || "";
    const published = role && role.publishedProfile && typeof role.publishedProfile === "object" ? role.publishedProfile : {};
    const publishedMission = cleanDisplayText(published.mission);
    if (publishedMission) return publishedMission;
    const authoredMission = cleanDisplayText(role && role.mission);
    if (authoredMission) return authoredMission;
    return OFFICE_ROLE_MISSION_EN[roleId] || cleanDisplayText(role && role.tagline);
  }
  function officeTimeDisplay(value) {
    const raw = cleanDisplayText(value);
    if (!raw) return "";
    if (raw === "剛剛") return "Just now";
    if (raw === "今天") return "Today";
    if (raw === "昨天") return "Yesterday";
    if (raw === "夜間排程") return "Overnight schedule";
    return raw
      .replace(/^今天(?=\s|$)/, "Today")
      .replace(/^昨天(?=\s|$)/, "Yesterday")
      .replace(/(^|\s·\s)夜間排程(?=$|\s·\s)/g, "$1Overnight schedule");
  }
  function officeActionDisplay(value) {
    const raw = cleanDisplayText(value);
    return OFFICE_ACTION_EN[raw] || raw;
  }
  function officeSourceDisplay(value) {
    const raw = cleanDisplayText(value);
    return OFFICE_SOURCE_EN[raw] || raw;
  }
  function runTaskDisplay(run, office, rawName) {
    const role = run && office && office.roleById && office.roleById[run.roleId];
    const skills = (role && role.skills) || [];
    const skill = skills.find((row) => (run.skillId && row.id === run.skillId) || row.name === rawName);
    if (skill && window.skillCopy) return window.skillCopy(role.id, skill, "name");
    return RUN_TASK_EN[rawName] || rawName;
  }
  function runTriggerDisplay(trigger, run, office) {
    const raw = cleanDisplayText(trigger && trigger.label);
    if (!raw) return "Work";
    if (RUN_TRIGGER_EN[raw]) return RUN_TRIGGER_EN[raw];
    if (raw.indexOf("同事轉入：") === 0) {
      const rawRole = cleanDisplayText(raw.slice("同事轉入：".length));
      const roles = (office && office.roles) || [];
      const role = roles.find((row) => row.title === rawRole || row.short === rawRole);
      return "Routed from: " + (role ? officeRoleName(role, role.id) : (OFFICE_ROLE_SEED_NAME_EN[rawRole] || rawRole));
    }
    if (raw.indexOf("Repeat work · ") === 0) {
      const rawTask = cleanDisplayText(raw.slice("Repeat work · ".length));
      return "Repeat work · " + runTaskDisplay(run, office, rawTask);
    }
    return raw;
  }
  function runCaveatDisplay(value) {
    const raw = cleanDisplayText(value);
    return RUN_CAVEAT_EN[raw] || raw;
  }
  function runSourceDisplay(value) { return officeSourceDisplay(value); }

  function RoleIcon({ role, size = 26 }) {
    return h("span", { style: { width: size, height: size, borderRadius: Math.max(8, size * 0.3), display: "grid", placeItems: "center", background: role ? role.color : "var(--bg-3)", color: "#fff", flex: "none" } },
      h(Icon, { name: ROLE_ICONS[role && role.id] || "users", size: Math.max(14, size * 0.52), color: "#fff" }));
  }
  function RoleDot({ role, size = 10 }) {
    return h("span", { style: { width: size, height: size, borderRadius: "50%", background: role ? role.color : "var(--border)", display: "inline-block", flex: "none" } });
  }
  // Face — dashboard ergonomics over window.OfficeFace (the floor voxel portrait).
  // Accepts a role object OR a roleId; default aria/title = the role's English short name.
  function Face({ role, roleId, size = 34, variant = "portrait", status, title, className }) {
    const id = roleId || (role && role.id);
    const label = title || officeRoleName(role, id);
    if (!window.OfficeFace || !id) return h(RoleDot, { role: role || { color: "var(--border)" }, size: Math.max(8, Math.round(size * 0.3)) });
    return h(window.OfficeFace, { roleId: id, size, variant, status, title: label, className });
  }
  function InlineIcon({ name, tone = "", size = 14 }) {
    return h("span", { className: ["inline-icon", tone].filter(Boolean).join(" ") }, h(Icon, { name, size }));
  }
  function StatusIcon({ ok }) {
    return h("span", { className: "status-icon " + (ok ? "ok" : "bad") }, h(Icon, { name: ok ? "check" : "x", size: 12 }));
  }
	  function Chip({ children, tone = "gray", style, title, ...rest }) {
	    return h("span", Object.assign({ className: "chip chip-" + tone, style, title }, rest), children);
  }
  // autonomy level chip — count/level isolated so the static copy is a matchable node (C11-iii)
  function levelChip(level) {
    return level === 2
      ? h(Chip, { tone: "mint" }, "Low-risk repeat work · 10-minute undo")
      : h(Chip, { tone: "purple" }, "Approval required");
  }
  function caveatLine(text) {
    return h("div", { className: "caveat-line" }, h(Icon, { name: "alert", size: 13 }), h("span", null, text));
  }
  // outcome split bar — each percentage in its own span; the captions are
  // English keyed to the office 繁中 so the i18n layer localizes them (C3/C11).
  function Seg3({ ok, ed, bk }) {
    return h(React.Fragment, null,
      h("div", { className: "seg3" },
        h("i", { className: "s-ok", style: { width: ok + "%" } }),
        h("i", { className: "s-ed", style: { width: ed + "%" } }),
        h("i", { className: "s-bk", style: { width: bk + "%" } })),
      h("div", { style: { fontSize: 11.5, color: "var(--text-faint)" } },
        h("span", null, "Approved "), h("span", null, ok + "%"), h("span", null, " · "),
        h("span", null, "Approved with edits "), h("span", null, ed + "%"), h("span", null, " · "),
        h("span", null, "Returned "), h("span", null, bk + "%")));
  }
  // audit-action -> tone. Keys stay 繁中 (logic keys on the 繁中 data values — C3).
  const AUDIT_TONE = { "核准": "mint", "自動執行": "mint", "修改後核准": "blue", "退回": "red", "政策封鎖": "red", "撤回": "gray", "聘用請求": "amber", "核准聘用": "mint", "退回聘用": "red", "建立任務": "blue", "建立工作單": "blue", "完成工作單": "mint", "重開工作單": "violet", "指派工具": "blue", "移除工具": "gray", "上傳檔案": "amber", "歸檔檔案": "mint", "發布設定": "violet", "還原設定": "amber", "匯出": "blue", "連接器連線": "mint", "重新授權": "blue", "中斷連接": "gray", "健康檢查": "blue", "整合需求": "amber", "更新設定": "violet", "更新公司": "blue", "邀請用戶": "mint", "更新用戶": "blue", "更新用戶權限": "violet", "重寄邀請": "blue", "停用用戶": "amber", "恢復用戶": "mint", "移除用戶": "red" };

  Object.assign(window, {
    RoleIcon, RoleDot, Face, InlineIcon, StatusIcon, Chip, levelChip, caveatLine, Seg3, AUDIT_TONE, ROLE_ICONS,
    OFFICE_ROLE_NAME_EN, OFFICE_ROLE_MISSION_EN, OFFICE_ACTION_EN,
    officeRoleName, officeRoleMission, officeTimeDisplay, officeActionDisplay, officeSourceDisplay,
    runTriggerDisplay, runCaveatDisplay, runSourceDisplay,
  });
})();
