// screen_ops.jsx — internal ops/admin screens (D1/D2/D3). Read-only ops block now
// lives in the unified store: ctx.office.ops (was window.OPS), single connector
// roster = ctx.office.connectors (C7). Every figure traces to a real office signal
// (Drive de-auth, IG error 2207026, stale approvals, connectors/kpi/inbox) — no
// fabricated wins, no zero-error perfection, 2026-API caveats kept. RBAC-gated.
(function () {
  const { useState, useEffect } = React;
  const h = React.createElement;
  window.Screens = window.Screens || {};

  // status / severity -> badge tone (reuse existing palette; no new tier invented)
  const HEALTH_TONE = { ok: "green", warn: "amber", down: "red" };
  const HEALTH_LABEL = { ok: "Working", warn: "Slow", down: "Unavailable" };
  const SEV_TONE = { low: "green", med: "amber", high: "red" };
  const SEV_LABEL = { low: "Low", med: "Medium", high: "High" };
  const INC_STATUS_TONE = { open: "red", monitoring: "amber", resolved: "green" };
  const INC_STATUS_LABEL = { open: "Unresolved", monitoring: "Watching", resolved: "Resolved" };
  const HAS_CJK = /[\u3400-\u9fff]/;
  const HEALTH_SEED_COPY = {
    "Email · Gmail": { detail: "Email updates are working. Last check: today 09:41.", since: "Today 09:41" },
    Instagram: { detail: "A video failed yesterday at 19:00 and worked on retry at 19:04. Today's limit: 8/100.", since: "Yesterday 19:04" },
    "Google Drive 同步": { system: "Google Drive", detail: "Access was removed. File updates are paused until you reconnect.", since: "Yesterday 21:14" },
    "我的辦公桌 · 任務派發": { system: "My Desk · task routing", detail: "Drafts are routing normally. Approval is still needed before sending.", since: "Today 10:55" },
  };
  const INCIDENT_SEED_COPY = {
    "INC-2041": { title: "Google Drive updates paused", source: "Google Drive app", opened: "Yesterday 21:14", detail: "Access was removed in Google account settings. Reconnect to add missed files." },
    "INC-2039": { title: "Instagram video timed out", source: "Instagram app", opened: "Yesterday 19:00", detail: "The video failed, then worked on retry at 19:04. Today's limit is 8/100." },
    "INC-2036": { title: "Some emails went to the wrong employee", source: "Email app", opened: "This month", detail: "Four emails were reassigned this month. The routing rule was updated." },
  };
  function plainOpsText(value) {
    return String(value || "")
      .replace(/Connectors?/gi, (match) => /s$/i.test(match) ? "Apps" : "App")
      .replace(/Incidents?/gi, (match) => /s$/i.test(match) ? "Issues" : "Issue")
      .replace(/Credentials?/gi, "Connection")
      .replace(/re-?authori[sz]ation/gi, "reconnect")
      .replace(/webhooks?/gi, "connection");
  }
  function healthDisplay(row) {
    const seed = HEALTH_SEED_COPY[row && row.system] || {};
    const time = row && row.since;
    return {
      system: seed.system || plainOpsText(row && row.system),
      detail: HAS_CJK.test(String(row && row.detail || "")) ? (seed.detail || "Check this system.") : plainOpsText(row && row.detail),
      since: HAS_CJK.test(String(time || "")) ? (seed.since || (window.officeTimeText ? window.officeTimeText(time) : "Recently")) : (window.officeTimeText ? window.officeTimeText(time) : time),
    };
  }
  function incidentDisplay(row) {
    const seed = INCIDENT_SEED_COPY[row && row.id] || {};
    const field = (name, fallback) => HAS_CJK.test(String(row && row[name] || "")) ? (seed[name] || fallback) : plainOpsText(row && row[name]);
    return {
      title: field("title", "App issue"),
      source: field("source", "App"),
      opened: field("opened", window.officeTimeText ? window.officeTimeText(row && row.opened) : "Recently"),
      detail: field("detail", "Check the app and try again."),
    };
  }

  // ---- D1 · System Health + Incidents ----
  function OpsHealth({ ctx }) {
    const { PageHeader, Card, CardHead, Badge, Button } = window;
    const OPS = (ctx.office && ctx.office.ops) || { health: [], incidents: [] };
    const health = OPS.health || [];
    const incidents = OPS.incidents || [];
    const downCount = health.filter((s) => s.status === "down").length;
    const warnCount = health.filter((s) => s.status === "warn").length;
    const openInc = incidents.filter((i) => i.status !== "resolved").length;
    const canRecheck = ctx.can("recheckOps");
    useEffect(() => {
      if (!ctx.pageArg) return;
      const t = window.setTimeout(() => {
        const el = document.getElementById("health-system-" + ctx.pageArg);
        if (el && el.scrollIntoView) el.scrollIntoView({ block: "center", behavior: "smooth" });
      }, 80);
      return () => window.clearTimeout(t);
    }, [ctx.pageArg]);

    return h("div", { "data-health-screen": "true", "data-health-down-count": String(downCount), "data-health-warn-count": String(warnCount), "data-health-open-incidents": String(openInc) },
      h(PageHeader, { eyebrow: "Operations", title: "System Status",
        sub: "See app updates, approvals and unresolved issues in one place.",
        right: h(Button, { icon: "refresh", disabled: !canRecheck, title: canRecheck ? "" : ctx.denyReason("recheckOps"), "data-health-action": "recheck", onClick: () => ctx.recheckOps() }, "Check again") }),

      // summary chips
      h("div", { style: { display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 18 } },
        [["Systems checked", health.length, "blue", "apps and approvals"],
         ["Working", health.filter((s) => s.status === "ok").length, "green", "no action needed"],
         ["Needs attention", warnCount + downCount, downCount ? "red" : (warnCount ? "amber" : "green"), warnCount + " slow · " + downCount + " unavailable"],
         ["Unresolved issues", openInc, openInc ? "amber" : "green", incidents.length + " total this period"]].map((m, i) =>
          h(Card, { key: i, style: { padding: 16 } },
            h("div", { className: "mono", style: { fontSize: 24, fontWeight: 700, color: `var(--${m[2]})` } }, String(m[1])),
            h("div", { style: { fontSize: 12, color: "var(--text-dim)", marginTop: 5, fontWeight: 500 } }, m[0]),
            h("div", { style: { fontSize: 11, color: "var(--text-faint)", marginTop: 3 } }, m[3])))),

      h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" } },
        // health list
        h(Card, null,
          h(CardHead, { title: "System status", sub: health.length + " systems", icon: "server" }),
          h("div", { style: { padding: 8 } },
            health.map((s, i) => {
              const sid = window.healthSystemId ? window.healthSystemId(s, i) : String(s.connectorId || s.system || ("system-" + (i + 1))).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
              const active = ctx.pageArg === sid;
              const display = healthDisplay(s);
              return h("div", { key: sid, id: "health-system-" + sid, "data-health-system-id": sid, "data-health-status": s.status || "", "data-health-active": active ? "true" : "false", "data-health-connector-id": s.connectorId || "", role: "button", tabIndex: 0, className: "row between health-system" + (active ? " onboard-hl" : ""), onClick: () => ctx.openPage("health", sid), onKeyDown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); ctx.openPage("health", sid); } },
                style: { padding: "12px 12px", borderBottom: i < health.length - 1 ? "1px solid var(--border)" : "none", gap: 12, alignItems: "flex-start", cursor: "pointer", background: active ? "var(--blue-soft)" : "transparent", borderRadius: active ? 10 : 0 } },
                h("div", { style: { minWidth: 0 } },
                  h("div", { className: "row gap8", style: { marginBottom: 4 } },
                    h(window.Icon, { name: "dot", size: 13, color: `var(--${HEALTH_TONE[s.status]})` }),
                    h("span", { style: { fontSize: 13.5, fontWeight: 600 } }, display.system)),
                  h("div", { style: { fontSize: 12, color: "var(--text-dim)", lineHeight: 1.5 } }, display.detail),
                  h("div", { style: { fontSize: 11, color: "var(--text-faint)", marginTop: 3 } }, h("span", null, "Since"), " ", h("span", null, display.since))),
                h(Badge, { tone: HEALTH_TONE[s.status] }, HEALTH_LABEL[s.status]));
            }))),

        // incidents
        h(Card, null,
          h(CardHead, { title: "Issues", sub: openInc + " unresolved · " + incidents.length + " total", icon: "alert" }),
          h("div", { style: { padding: 8 } },
            incidents.length === 0
              ? h("div", { style: { padding: 18, fontSize: 13, color: "var(--text-faint)" } }, "No issues recorded this period.")
              : incidents.map((inc, i) => {
                const display = incidentDisplay(inc);
                return h("button", { key: inc.id, type: "button", className: "row-link", "data-incident-id": inc.id, "data-incident-action": "open", "data-incident-status": inc.status || "", "data-incident-severity": inc.severity || "", "data-incident-connector-id": inc.connectorId || "", onClick: () => ctx.openPage("incident", inc.id),
                  style: { width: "100%", textAlign: "left", padding: "12px 12px", border: 0, background: "transparent", borderBottom: i < incidents.length - 1 ? "1px solid var(--border)" : "none", cursor: "pointer" } },
                  h("div", { className: "row between", style: { gap: 10, marginBottom: 4 } },
                    h("span", { className: "row gap8" },
                      h("span", { className: "mono", style: { fontSize: 11, color: "var(--text-faint)" } }, inc.id),
                      h(Badge, { tone: SEV_TONE[inc.severity] }, SEV_LABEL[inc.severity])),
                    h(Badge, { tone: INC_STATUS_TONE[inc.status], dot: true }, INC_STATUS_LABEL[inc.status])),
                  h("div", { style: { fontSize: 13, fontWeight: 600 } }, display.title),
                  h("div", { style: { fontSize: 11.5, color: "var(--text-faint)", marginTop: 3 } }, h("span", null, display.source), " · ", h("span", null, display.opened)));
              })))));
  }

  function IncidentDetail({ ctx }) {
    const { PageHeader, Card, Section, Badge, Button, Icon, Chip } = window;
    const [confirmAction, setConfirmAction] = useState(false);
    const OPS = (ctx.office && ctx.office.ops) || { incidents: [] };
    const inc = (OPS.incidents || []).find((x) => x.id === ctx.pageArg);
    if (!inc) {
      return h("div", null,
        h(PageHeader, { eyebrow: "Operations", title: "Issue not found",
          sub: "This issue may be resolved or no longer shown.",
          right: h(Button, { sm: true, onClick: () => ctx.openPage("health") }, "Back to System Status") }),
        h(Card, { style: { padding: 24 } }, h(window.EmptyHint, { icon: "alert", text: "No issue matches #" + (ctx.pageArg || "unknown") + "." })));
    }
    const connectorId = ctx.connectorForIncident(inc);
    const display = incidentDisplay(inc);
    const connector = connectorId ? (ctx.office.connectors || []).find((x) => x.id === connectorId) : null;
    const connectorName = connector ? ((window.CONN_NAME_EN && window.CONN_NAME_EN[connector.id]) || connector.name) : null;
    const disconnected = !!(connector && connector.status !== "已連接");
    const needsReauth = !!(connector && !disconnected && connector.health && connector.health !== "ok" && inc.status !== "resolved");
    const actionMode = disconnected ? "connect" : needsReauth ? "reauth" : null;
    const canAction = actionMode ? ctx.can(actionMode) : true;
    const canRecheck = ctx.can("recheckOps");
    const canExport = ctx.can("export");
    function remediationStrip() {
      if (!connector) return null;
      const healthy = !actionMode;
      const actionLabel = actionMode === "connect" ? "Connect " + connectorName : "Reconnect " + connectorName;
      return h("div", { className: "incident-action" + (healthy ? " ok" : ""), "data-incident-remediation": actionMode || "healthy", "data-incident-connector-id": connector.id },
        h("div", { className: "incident-action-head" },
          h("div", { className: "incident-action-copy" },
            h("div", { className: "eyebrow", style: { marginBottom: 5 } }, "Recommended action"),
            h("b", null, healthy ? connectorName + " is working" : actionMode === "connect" ? "Reconnect " + connectorName : "Reconnect " + connectorName),
            h("span", null, healthy
              ? "Check again, or open the app to see its history."
              : actionMode === "connect"
	                ? "Reconnect the app and check for new items."
                : "Reconnect the app and add any missed items.")),
          h("div", { className: "row gap6 wrap", style: { justifyContent: "flex-end" } },
            h(Chip, { tone: healthy ? "green" : "amber" }, healthy ? "Connected" : "Reconnect needed"),
            h(Button, { sm: true, variant: "ghost", iconRight: "arrowRight", "data-incident-action": "open-connector", "data-incident-connector-id": connector.id, onClick: () => ctx.openPage("connector", connector.id) }, "Open app"),
            healthy
              ? h(Button, { sm: true, variant: "primary", icon: "refresh", disabled: !canRecheck, title: canRecheck ? "" : ctx.denyReason("recheckOps"), "data-health-action": "recheck-detail", "data-incident-action": "recheck", "data-incident-connector-id": connector.id, onClick: () => ctx.recheckOps() }, "Check again")
              : h(Button, { sm: true, variant: "primary", icon: "link", disabled: !canAction, title: canAction ? "" : ctx.denyReason(actionMode), "data-incident-action": actionMode, "data-incident-connector-id": connector.id, onClick: () => setConfirmAction(true) }, actionLabel))),
        confirmAction && !healthy && h("div", { className: "incident-confirm", "data-incident-confirm": actionMode, "data-incident-connector-id": connector.id },
          h("div", { className: "row gap8 wrap" },
            h(Icon, { name: "shield", size: 15 }),
            h("b", { style: { fontSize: 13 } }, actionMode === "connect" ? "Connect app" : "Reconnect app"),
            h("span", { className: "mono" }, connector.connectFlow && connector.connectFlow.account ? connector.connectFlow.account : connectorName)),
          h("div", { style: { color: "var(--text-dim)", fontSize: 12.5, lineHeight: 1.5 } },
            actionMode === "connect"
              ? "This connects the app, checks for new items, and saves the change in History."
              : "This reconnects the app, adds missed items, and saves the change in History."),
          h("div", { className: "row gap6 wrap" },
            h(Button, { sm: true, variant: "ghost", "data-incident-action": "cancel-confirm", "data-incident-connector-id": connector.id, onClick: () => setConfirmAction(false) }, "Cancel"),
            h(Button, { sm: true, variant: "primary", icon: "check", "data-incident-action": actionMode === "connect" ? "confirm-connect" : "confirm-reauth", "data-incident-connector-id": connector.id, onClick: () => { actionMode === "connect" ? ctx.connect(connector.id) : ctx.reauth(connector.id); setConfirmAction(false); } }, actionMode === "connect" ? "Connect" : "Reconnect"))));
    }
    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-incident-detail": inc.id, "data-incident-status": inc.status || "", "data-incident-severity": inc.severity || "", "data-incident-connector-id": connectorId || "" },
      h(PageHeader, { eyebrow: "Operations", title: "Issue · " + inc.id, icon: "alert",
        sub: display.title,
        right: [
          h(Button, { key: "back", sm: true, variant: "ghost", "data-incident-action": "back", onClick: () => ctx.openPage("health") }, "Back to System Status"),
          connectorId && h(Button, { key: "conn", sm: true, variant: "ghost", iconRight: "arrowRight", "data-incident-action": "open-connector", "data-incident-connector-id": connectorId, onClick: () => ctx.openPage("connector", connectorId) }, "Open app"),
          h(Button, { key: "export", sm: true, variant: "primary", icon: "download", disabled: !canExport, title: canExport ? "" : ctx.denyReason("export"), "data-incident-action": "export", "data-incident-id": inc.id, onClick: () => ctx.exportJson("incident-" + inc.id + ".json", inc, "Issue " + inc.id) }, "Download issue"),
        ] }),
      h(Card, { style: { padding: 18 } },
        h("div", { className: "row gap8", style: { marginBottom: 20, flexWrap: "wrap" } },
          h(Badge, { tone: SEV_TONE[inc.severity] }, SEV_LABEL[inc.severity] + " priority"),
          h(Badge, { tone: INC_STATUS_TONE[inc.status], dot: true }, INC_STATUS_LABEL[inc.status])),
        remediationStrip(),
        h(Section, { title: "Details" }, h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(180px,1fr))", gap: 16 } },
          meta("Reported by", display.source), meta("Opened", display.opened), connectorName && meta("App", connectorName))),
        h(Section, { title: "What happened", style: { marginBottom: 0 } },
          h("div", { style: { padding: 13, borderRadius: 11, background: "var(--bg-3)", border: "1px solid var(--border)", fontSize: 12.5, color: "var(--text-dim)", lineHeight: 1.55 } }, display.detail))));
  }

  window.Screens.health = OpsHealth;
  window.Screens.incident = IncidentDetail;
})();
