// screen_audit_settings.jsx — Audit Log + Settings
(function () {
  const { useState, useEffect } = React;
  const h = React.createElement;
  window.Screens = window.Screens || {};
  function plainHistoryText(value) {
    return String(value || "")
      .replace(/Approval Desk/gi, "My Desk")
      .replace(/Training Room/gi, "Employee Tasks")
      .replace(/Mail Room/gi, "Apps")
      .replace(/Work Orders?/gi, (match) => /s$/i.test(match) ? "Tasks" : "Task")
      .replace(/Role Configuration/gi, "Employee settings")
      .replace(/File Room/gi, "Files")
      .replace(/Connectors?/gi, (match) => /s$/i.test(match) ? "Apps" : "App");
  }

  function AuditEventDetail({ ctx }) {
    const D = window.deriveDashboardData(ctx.office);
    const { PageHeader, Card, Section, Badge, RiskBadge, Button } = window;
    const RES = { Allowed: "green", Denied: "red", "Pending Approval": "amber" };
    const resultLabel = (value) => ({ Allowed: "Allowed", Denied: "Blocked", "Pending Approval": "Waiting approval" }[value] || value);
    const r = D.audit.find((row) => row.sid === ctx.pageArg);
    if (!r) {
      return h("div", { "data-audit-not-found": ctx.pageArg || "", "data-audit-missing-id": ctx.pageArg || "unknown" },
        h(PageHeader, { eyebrow: "History", title: "History record not found",
          sub: "This link does not match a current record.",
          right: h(Button, { sm: true, "data-audit-action": "back", onClick: () => ctx.openPage("audit") }, "Back to History") }),
        h(Card, { style: { padding: 24 } }, h(window.EmptyHint, { icon: "scroll", text: "No history record matches #" + (ctx.pageArg || "unknown") + "." })));
	    }
	    const raw = (ctx.office.auditLog || []).find((row) => row.id === r.sid);
	    const canRollback = !!(raw && raw.action === "發布設定" && raw.rollbackState && raw.rollbackState.roleState && ctx.can("configure"));
	    const canExport = ctx.can("export");
	    const canExportRawAudit = raw && ctx.can("configure");
	    const rollbackTitle = raw && raw.rollbackState ? "Undo to v" + (raw.rollbackState.previousVersion || Math.max(((raw.publishedState && raw.publishedState.version) || 1) - 1, 1)) : "Undo changes";
	    const exportPayload = canExportRawAudit ? Object.assign({ display: r }, raw) : r;
	    const e = D.emp(r.emp);
	    const meta = (l, v) => h("div", null, h("div", { style: { fontSize: 10.5, color: "var(--text-faint)", fontWeight: 700, letterSpacing: ".06em", marginBottom: 5 } }, l.toUpperCase()), h("div", { style: { fontSize: 13, fontWeight: 500 } }, v));
		    return h("div", { "data-audit-detail": r.sid, "data-audit-detail-id": r.sid, "data-audit-id": r.sid, "data-audit-result": r.result || "", "data-audit-risk": r.risk || "", "data-audit-role-id": r.emp || "", "data-audit-rollback-available": canRollback ? "true" : "false", "data-audit-rollback-consumed-by": raw && raw.rollbackConsumedBy || "" },
	      h(PageHeader, { eyebrow: "History", title: "History record · " + r.sid, icon: "scroll",
	        sub: plainHistoryText(r.action),
		        right: [
		          h(Button, { key: "back", sm: true, variant: "ghost", "data-audit-action": "back", onClick: () => ctx.openPage("audit") }, "Back to History"),
		          raw && raw.action === "發布設定" && h(Button, { key: "rollback", sm: true, icon: "refresh", disabled: !canRollback,
		            "data-audit-action": "rollback",
		            "data-audit-action-kind": "rollback-config",
		            "data-audit-id": r.sid,
		            "data-audit-role-id": raw.roleId || "",
		            "data-audit-rollback-available": canRollback ? "true" : "false",
		            "data-audit-rollback-consumed-by": raw.rollbackConsumedBy || "",
	            title: canRollback ? "Restore the previous employee settings." : ctx.can("configure") ? "This change was already undone, or there is nothing to restore." : ctx.denyReason("configure"),
		            onClick: canRollback ? () => ctx.rollbackConfigVersion(raw.roleId, raw.publishedState && raw.publishedState.version, raw.rollbackState) : undefined }, rollbackTitle),
	          h(Button, { key: "export", sm: true, variant: "primary", icon: "download", disabled: !canExport, title: canExport ? "" : ctx.denyReason("export"), "data-audit-action": "export-event", "data-audit-export": "event", "data-audit-export-scope": canExportRawAudit ? "raw" : "display", "data-audit-id": r.sid, onClick: () => ctx.exportJson("history-record-" + r.sid + ".json", exportPayload, "History record " + r.sid) }, "Download record"),
		        ] }),
      h(Card, { style: { padding: 18 } },
        h("div", { className: "row gap8", style: { marginBottom: 22, flexWrap: "wrap" } }, h(Badge, { tone: RES[r.result], dot: true }, resultLabel(r.result)), h(RiskBadge, { level: r.risk })),
        h(Section, { title: "Details" }, h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(180px,1fr))", gap: 16 } },
          meta("AI Employee", r.emp === "—" ? "System" : h("span", { className: "row gap8" }, h(window.Face, { roleId: e.id, size: 22, variant: "head" }), e.short)),
          meta("App or file", plainHistoryText(r.tool)), meta("Approver", r.approver), meta("Record ID", h("span", { className: "mono", style: { fontSize: 12 } }, r.sid)))),
        h(Section, { title: "Time", style: { marginBottom: 0 } }, h("div", { className: "mono", style: { fontSize: 13, color: "var(--text-dim)" } }, r.ts),
          h("div", { style: { marginTop: 12, padding: 13, borderRadius: 11, background: "var(--bg-3)", border: "1px solid var(--border)", fontSize: 12.5, color: "var(--text-dim)", lineHeight: 1.5 } },
	            "Read-only record. Download a copy if needed."))));
  }

  function Audit({ ctx }) {
    const lang = window.useScenarioLang ? window.useScenarioLang() : (window.I18N ? window.I18N.getLang() : "en");
    const ui = (s) => (window.scenarioUiText ? window.scenarioUiText(s, lang) : ((window.I18N && lang !== "en") ? window.I18N.t(s) : s));
    const person = (s) => String(s || "").split(" · ").map((part) => ui(part)).join(" · ");
    const D = window.deriveDashboardData(ctx.office);
    const { PageHeader, Card, CardHead, Badge, RiskBadge, Button, Avatar, Segmented } = window;
    const [f, setF] = useState("All");
    const rows = f === "All" ? D.audit : D.audit.filter((r) => r.result === f);
    const RES = { Allowed: "green", Denied: "red", "Pending Approval": "amber" };
    const resultLabel = (value) => ({ Allowed: "Allowed", Denied: "Blocked", "Pending Approval": "Waiting approval" }[value] || value);
    const canExport = ctx.can("export");
    const filterSlug = (value) => value.toLowerCase().replace(/\s+/g, "-");
    const filterOptions = ["All", "Allowed", "Denied", "Pending Approval"].map((value) => ({
      value,
      label: resultLabel(value),
      attrs: { "data-audit-filter": value, "data-audit-filter-option": filterSlug(value), "data-audit-filter-active": f === value ? "true" : "false" }
    }));
    // QA coverage — scores 100% of logged actions (demo heuristic, not certified scoring).
    const QA = D.audit.map((r) => r.result === "Allowed" ? { pass: true } : { pass: false });
    const qaPass = QA.filter((q) => q.pass).length;
    const qaPct = D.audit.length ? Math.round((qaPass / D.audit.length) * 100) : 0;
    const qaFlagged = D.audit.length - qaPass;

	    return h("div", { "data-audit-screen": "true", "data-audit-root": "log", "data-audit-filter": f, "data-audit-filter-value": f, "data-audit-row-count": String(rows.length), "data-audit-total-count": String(D.audit.length), "data-audit-qa-pct": String(qaPct) },
      h(PageHeader, { eyebrow: "History", title: "History",
	        sub: "See actions, files, and approvals.",
        right: [h(Segmented, { key: "f", value: f, onChange: setF, options: filterOptions }), h(Button, { key: "e", icon: "download", disabled: !canExport, title: canExport ? "" : ctx.denyReason("export"), "data-audit-action": "export-log", "data-audit-export": "log", "data-audit-export-filter": f, "data-audit-export-count": String(rows.length), onClick: () => ctx.exportCsv("emplix-history-" + f.toLowerCase().replace(/\s+/g, "-") + ".csv", rows, [
	          { key: "ts", label: "Time" },
          { key: "emp", label: "AI Employee" },
          { key: "action", label: "Action" },
          { key: "tool", label: "App or file" },
          { key: "result", label: "Result", value: (row) => resultLabel(row.result) },
          { key: "approver", label: "Approver" },
          { key: "risk", label: "Risk" },
          { key: "sid", label: "Record ID" },
          { key: "note", label: "Note" },
        ], "History download", rows.length + " records") }, "Download")] }),
      h(Card, { style: { marginBottom: 16 } },
        h(CardHead, {
          title: lang === "en" ? "Review summary" : "覆核摘要",
          sub: lang === "en" ? "Actions allowed or marked for review." : "已允許或已標示覆核的動作。",
          icon: "shield",
          right: h(Badge, { tone: qaFlagged === 0 ? "green" : "amber" }, lang === "en" ? qaFlagged + " need review" : qaFlagged + " 個需覆核") }),
        h("div", { style: { padding: "10px 16px 16px", fontSize: 12.5, color: "var(--text-dim)", lineHeight: 1.6 } },
          lang === "en"
            ? [h("b", { key: "p" }, qaPass), " allowed; ", h("b", { key: "f" }, qaFlagged), " need review. A blocked action can still be the correct result."]
            : [h("b", { key: "p" }, qaPass), " 個已允許；", h("b", { key: "f" }, qaFlagged), " 個需覆核。已阻擋的動作仍可能是正確結果。"])),
      h(Card, null,
        h(CardHead, { title: "Records", sub: lang === "en" ? rows.length + " records · " + ctx.env : rows.length + " 個紀錄 · " + ui(ctx.env), icon: "scroll",
          right: ctx.approver
            ? h(Badge, { tone: "blue" }, h(window.Icon, { name: "shield", size: 11 }), lang === "en" ? "Saved under · " + ctx.approver : "記錄於 · " + person(ctx.approver))
            : h(Badge, { tone: "neutral" }, h(window.Icon, { name: "eye", size: 11 }), ui("Viewer — read-only, not an approver")) }),
        h("div", { style: { overflowX: "auto" } },
          h("table", { className: "tbl" },
            h("thead", null, h("tr", null, ["Time", "AI employee", "Action", "App or file", "Result", "Approver", "Risk", "Record ID"].map((c, i) => h("th", { key: i }, c)))),
            h("tbody", null, rows.map((r) => { const e = D.emp(r.emp);
              return h("tr", { key: r.sid, className: "row-link", "data-audit-row": r.sid, "data-audit-event-id": r.sid, "data-audit-result": r.result || "", "data-audit-risk": r.risk || "", "data-audit-role-id": r.emp || "", "data-audit-row-action": r.action || "", role: "button", tabIndex: 0, onClick: () => ctx.openPage("audit-event", r.sid), onKeyDown: (ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); ctx.openPage("audit-event", r.sid); } } },
                h("td", { className: "mono", style: { fontSize: 11.5, color: "var(--text-dim)", whiteSpace: "nowrap" } }, r.ts),
                h("td", null, r.emp === "—" ? h("span", { className: "faint" }, "System") : h("span", { className: "row gap8" }, h(window.Face, { roleId: e.id, size: 24, variant: "head" }), h("span", { style: { fontSize: 12.5, fontWeight: 500 } }, e.short))),
                h("td", { style: { fontSize: 12.5 } }, plainHistoryText(r.action)),
                h("td", { className: "dim", style: { fontSize: 12.5 } }, plainHistoryText(r.tool)),
                h("td", null, h(Badge, { tone: RES[r.result], dot: true }, resultLabel(r.result))),
                h("td", { className: "dim", style: { fontSize: 12.5 } }, r.approver),
                h("td", null, h(RiskBadge, { level: r.risk })),
                h("td", { className: "mono", style: { fontSize: 11, color: "var(--text-faint)" } }, r.sid)); }))))));
  }

  function Settings({ ctx }) {
    const { PageHeader, Card, CardHead, Badge, Toggle, Segmented, Button } = window;
    const S = ctx.settings;
    const [workspaceDraft, setWorkspaceDraft] = useState({ workspaceLabel: S.workspaceLabel, region: S.region });
    useEffect(() => { setWorkspaceDraft({ workspaceLabel: S.workspaceLabel, region: S.region }); }, [S.workspaceLabel, S.region]);
    useEffect(() => {
      if (!ctx.pageArg) return;
      const t = window.setTimeout(() => {
        const el = document.getElementById("settings-section-" + ctx.pageArg);
        if (el && el.scrollIntoView) el.scrollIntoView({ block: "center", behavior: "smooth" });
      }, 80);
      return () => window.clearTimeout(t);
    }, [ctx.pageArg]);
		    const LEVEL_TONE = { owner: "green", manager: "blue", operator: "amber", viewer: "neutral" };
		    const canAccess = ctx.can("manageCompanyAccess");
		    const canManageSettings = ctx.can("manageCompanyUsers");
		    const settingsDenyReason = canManageSettings ? "" : ctx.denyReason("manageCompanyUsers");
		    function saveWorkspace() { ctx.updateWorkspaceSettings(workspaceDraft, "Workspace settings saved"); }
		    function segmentOptions(key, options, activeValue, extraAttrs) {
		      return (options || []).map((value) => ({
		        value,
		        label: value,
		        attrs: Object.assign({
		          "data-settings-segment": key,
		          "data-settings-option": value,
		          "data-settings-active": value === activeValue ? "true" : "false"
		        }, extraAttrs || {})
		      }));
		    }
    function sectionProps(id, extra) {
      extra = extra || {};
      return Object.assign({}, extra, {
        id: "settings-section-" + id,
        "data-settings-section": id,
        className: "settings-section" + (ctx.pageArg === id ? " onboard-hl" : "") + (extra.className ? " " + extra.className : "")
      });
    }
	    return h("div", { "data-settings-screen": "true", "data-settings-workspace": S.workspaceLabel || "", "data-settings-environment": S.defaultEnvironment || "", "data-settings-region": S.region || "" },
      h(PageHeader, { eyebrow: "Admin", title: "Settings",
	        sub: "Manage workspace, approvals, and alerts." }),
      h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" } },

        h(Card, sectionProps("workspace"), h(CardHead, { title: "Workspace", icon: "settings" }),
          h("div", { style: { padding: 18, display: "flex", flexDirection: "column", gap: 16 } },
            row("Client", h("input", { id: "settings-workspace-label", className: "field", value: workspaceDraft.workspaceLabel || "", disabled: !canManageSettings, title: settingsDenyReason, "data-settings-field": "workspaceLabel", onChange: (e) => setWorkspaceDraft((d) => Object.assign({}, d, { workspaceLabel: e.target.value })) }), "settings-workspace-label"),
            row("Default environment", h(Segmented, { value: S.defaultEnvironment, disabled: !canManageSettings, title: settingsDenyReason, onChange: (v) => ctx.updateWorkspaceSettings({ defaultEnvironment: v }, "Default environment") , options: segmentOptions("defaultEnvironment", window.deriveDashboardData(ctx.office).environments, S.defaultEnvironment) })),
            row("Region", h("input", { id: "settings-region", className: "field", value: workspaceDraft.region || "", disabled: !canManageSettings, title: settingsDenyReason, "data-settings-field": "region", onChange: (e) => setWorkspaceDraft((d) => Object.assign({}, d, { region: e.target.value })) }), "settings-region"),
            h("div", { className: "row gap8 wrap" },
              h(Button, { sm: true, variant: "primary", disabled: !ctx.can("manageCompanyUsers"), title: ctx.can("manageCompanyUsers") ? "" : ctx.denyReason("manageCompanyUsers"), "data-settings-action": "save-workspace", onClick: saveWorkspace }, "Save workspace"),
              h(Badge, { tone: "blue" }, "Saved in workspace settings")))),

        h(Card, sectionProps("governance"), h(CardHead, { title: "Approval defaults", icon: "shield" }),
          h("div", { style: { padding: 18, display: "flex", flexDirection: "column", gap: 14 } },
		            toggleRow("Approve new files", "requireSourceWriteApproval", S, ctx.updateWorkspaceSetting),
	            toggleRow("Pause on rule break", "autoPausePolicy", S, ctx.updateWorkspaceSetting),
		            row("Default work style", h(Segmented, { value: S.defaultAutonomy, disabled: !canManageSettings, title: settingsDenyReason, onChange: (v) => ctx.updateWorkspaceSettings({ defaultAutonomy: v }, "Default work style"), options: [
		              { value: "Observe", label: "Watch only", attrs: { "data-settings-segment": "defaultAutonomy", "data-settings-option": "Observe", "data-settings-active": S.defaultAutonomy === "Observe" ? "true" : "false" } },
		              { value: "Advise", label: "Suggest", attrs: { "data-settings-segment": "defaultAutonomy", "data-settings-option": "Advise", "data-settings-active": S.defaultAutonomy === "Advise" ? "true" : "false" } },
		            ] })),
		            h("div", { style: { padding: 14, borderRadius: 11, background: "var(--bg-3)", border: "1px solid var(--border)", fontSize: 12.5, color: "var(--text-dim)", lineHeight: 1.55 } },
		              h("strong", { style: { color: "var(--text)" } }, "Start with approval."), " ", "Allow repeat work only after it proves reliable.",
		              h("div", { style: { marginTop: 6 } }, S.requireSourceWriteApproval ? "New files wait for approval before they are saved." : "New files are saved right away and can be undone for 30 days."),
		              h("div", { style: { marginTop: 4 } }, S.autoPausePolicy ? "A rule break pauses the employee." : "Rule breaks are blocked and saved. New work continues.")))),

        h(Card, sectionProps("notifications"), h(CardHead, { title: "Notifications", icon: "bell" }),
          h("div", { style: { padding: 18, display: "flex", flexDirection: "column", gap: 14 } },
	            toggleRow("New approval requests", "notifyApprovalRequests", S, ctx.updateWorkspaceSetting),
	            toggleRow("Weekly value email", "weeklyRoiDigest", S, ctx.updateWorkspaceSetting),
		            toggleRow("Team chat issue alerts", "teamChatAlerts", S, ctx.updateWorkspaceSetting))),

        h(Card, sectionProps("access", { style: { gridColumn: "1 / -1" } }), h(CardHead, { title: "Team access", icon: "users",
	            sub: canAccess ? "Choose what each teammate can do." : "Owners change access. Managers can edit settings and invite people.",
            right: h(Button, { sm: true, iconRight: "arrowRight", "data-settings-action": "open-company", onClick: () => ctx.openPage("company") }, "Open Company & Team") }),
          h("div", { style: { padding: 8 } },
            ctx.team.map((m, i) =>
              h("div", { key: i, className: "row between", "data-settings-user-row": m.id, "data-settings-user-level": m.level, "data-settings-user-status": m.status, style: { padding: "11px 12px", borderBottom: i < ctx.team.length - 1 ? "1px solid var(--border)" : "none", flexWrap: "wrap", gap: 10 } },
                h("span", { className: "row gap10" },
                  h("div", { style: { width: 30, height: 30, borderRadius: 9, background: "var(--bg-3)", border: "1px solid var(--border)", display: "grid", placeItems: "center", fontSize: 12, fontWeight: 700, color: "var(--text-dim)" } }, m.name.split(" ").map((p) => p[0]).join("").slice(0, 2)),
                  h("div", null,
                    h("div", { style: { fontSize: 13, fontWeight: 600 } }, m.name),
                    m.level === ctx.actingLevel && h("div", { style: { fontSize: 10.5, color: "var(--green)", fontWeight: 700 } }, "Acting as · " + ctx.LEVEL_LABEL[m.level]))),
                h("span", { className: "row gap10" },
                  canAccess && h(Segmented, { value: m.level, onChange: (v) => { ctx.updateCompanyUser(m.id, { level: v }); }, options: ctx.LEVELS.map((l) => ({ value: l.id, label: l.label, attrs: { "data-settings-user-level-option": l.id, "data-settings-user-id": m.id, "data-settings-active": l.id === m.level ? "true" : "false" } })) }),
                  h(Badge, { tone: LEVEL_TONE[m.level] }, ctx.LEVEL_LABEL[m.level])))),
	            h("div", { style: { padding: "12px 12px 4px", fontSize: 11.5, color: "var(--text-faint)", lineHeight: 1.5 } },
	              "Approvals use your current role and are saved in History. Viewers cannot approve.")))));
	    function row(label, body, controlId) { return h("div", null, h(controlId ? "label" : "div", Object.assign({ style: { display: "block", fontSize: 12.5, fontWeight: 600, marginBottom: 7, color: "var(--text-dim)" } }, controlId ? { htmlFor: controlId } : {}), label), body); }
	    function toggleRow(label, key, settings, onToggle) {
	      const labelId = "settings-toggle-label-" + key;
	      return h("div", { className: "row between", "data-settings-toggle-row": key, style: { padding: "4px 0" } }, h("span", { id: labelId, style: { fontSize: 13.5, fontWeight: 500 } }, label), h(Toggle, { on: !!settings[key], disabled: !canManageSettings, title: settingsDenyReason, "aria-labelledby": labelId, "data-settings-toggle": key, "data-settings-toggle-on": settings[key] ? "true" : "false", onChange: (v) => onToggle(key, v, label) }));
	    }
  }

  window.Screens.audit = Audit;
  window.Screens["audit-event"] = AuditEventDetail;
  window.Screens.settings = Settings;
})();
