// screen_command.jsx — Command Center
(function () {
  const h = React.createElement;
  window.Screens = window.Screens || {};

  function CommandCenter({ ctx }) {
    const D = window.deriveDashboardData(ctx.office);
    const { Card, CardHead, KPI, Badge, Button } = window;

    const KPI_GO = {
      "AI Employees Active": "employees",
      "Tasks Completed": "workorders",
      "Hours Saved": "roi",
      "Estimated Cost Saved": "roi",
      "Pending Approvals": "approvals",
      "Approval Rate": "training",
      "Auto-sends": "roi",
      "Demo Operating Cost": "roi"
    };
    const KPI_LABEL = {
      "AI Employees Active": "Active AI employees",
      "Tasks Completed": "Tasks completed",
      "Hours Saved": "Hours saved",
      "Estimated Cost Saved": "Estimated savings",
      "Pending Approvals": "Waiting in My Desk",
      "Approval Rate": "Approval rate",
      "Auto-sends": "Approved repeat work",
      "Demo Operating Cost": "Sample cost"
    };
    const PRIMARY_KPIS = new Set(["Pending Approvals", "Tasks Completed", "Hours Saved", "Estimated Cost Saved"]);
    const recId = ctx.office.recommendedRole || (ctx.office.day0Seed && ctx.office.day0Seed.recommendedRole) || "clerk";
    const isEmptyOffice = !!(ctx.office.onboarding && ctx.office.onboarding.day0)
      || ((ctx.office.inbox || []).length === 0 && (ctx.office.auditLog || []).length === 0);

    const primaryAction = h(Button, {
      variant: "primary",
      icon: isEmptyOffice ? "plus" : "inbox",
      "data-command-primary-action": isEmptyOffice ? "give-first-task" : "open-approvals",
      "data-command-route": isEmptyOffice ? "employee/" + recId : "approvals",
      onClick: () => isEmptyOffice ? ctx.openPage("employee", recId) : ctx.setActive("approvals")
    }, isEmptyOffice ? "Give your first task" : "Open My Desk");

    const hero = h("header", {
      className: "command-hero",
      "data-command-overview-header": "true",
      style: {
        position: "relative",
        overflow: "hidden",
        borderRadius: "var(--radius-lg)",
        border: "1px solid var(--border)",
        padding: "30px 32px",
        marginBottom: 24,
        background: "linear-gradient(120deg, #edf6f2 0%, #f4f7ff 62%, #ffffff 100%)"
      }
    },
      h("div", { style: { position: "absolute", right: 0, top: 0, bottom: 0, width: 8, background: "linear-gradient(180deg,var(--blue),var(--green))" } }),
      h("div", { className: "command-hero-copy", style: { position: "relative", width: "calc(100% - 170px)", maxWidth: 760 } },
        h("div", { className: "row gap10 command-hero-kicker", style: { marginBottom: 14 } },
          h(Badge, { tone: "blue", dot: true }, ctx.env === "Demo" ? "Sample demo" : "Live · " + ctx.env),
          h(Badge, { tone: "green" }, h("span", { className: "live-dot", style: { width: 6, height: 6 } }), "4 AI employees active")),
        h("h1", { className: "command-title", style: { fontSize: 32, letterSpacing: "-0.03em", lineHeight: 1.05 } }, "Overview"),
        h("p", { style: { fontSize: 15.5, color: "var(--text-dim)", marginTop: 12, lineHeight: 1.55, maxWidth: 660 } }, "AI employees draft from your files, wait for approval, and show monthly value."),
        h("div", { className: "row gap10 command-proof", style: { marginTop: 18, flexWrap: "wrap" } },
          ["Approval before sending", "Sample files used", "Value shown as estimates"].map((text, index) =>
            h("span", { key: index, className: "row gap6", style: { fontSize: 12.5, color: "var(--text-dim)", fontWeight: 600 } },
              h(window.Icon, { name: "check", size: 14, color: "var(--green)" }), text)))),
      h("span", { className: "command-primary-action" }, primaryAction));

    const day0Hero = h("header", {
      className: "command-hero",
      "data-command-overview-header": "true",
      style: {
        position: "relative",
        overflow: "hidden",
        borderRadius: "var(--radius-lg)",
        border: "1px solid var(--border)",
        padding: "30px 32px",
        marginBottom: 24,
        background: "linear-gradient(120deg, #edf6f2 0%, #f4f7ff 62%, #ffffff 100%)"
      }
    },
      h("div", { style: { position: "absolute", right: 0, top: 0, bottom: 0, width: 8, background: "linear-gradient(180deg,var(--blue),var(--green))" } }),
      h("div", { style: { position: "relative", maxWidth: 720 } },
        h("div", { className: "row gap10", style: { marginBottom: 14 } },
          h(Badge, { tone: "blue", dot: true }, ctx.env === "Demo" ? "Sample demo" : "Live · " + ctx.env)),
        h("h1", { className: "command-title", style: { fontSize: 30, letterSpacing: "-0.03em", lineHeight: 1.08 } }, "Give your first task"),
        h("p", { style: { fontSize: 15.5, color: "var(--text-dim)", marginTop: 12, lineHeight: 1.55, maxWidth: 600 } }, "Drafts wait in My Desk."),
        h("div", { className: "row gap10", style: { marginTop: 20, flexWrap: "wrap" } },
          primaryAction,
          h(Button, { variant: "ghost", onClick: () => ctx.openPage("floor") }, "Open the Floor View"))));

    const floorHero = h("a", {
      className: "floor-hero",
      href: "#floor",
      "aria-label": "Open Floor View",
      "data-command-floor-hero": "true",
      "data-floor-action": "open-floor",
      "data-floor-open-target": "floor",
      onClick: (event) => { event.preventDefault(); ctx.openPage("floor"); },
      title: "Open Floor View"
    },
      h("div", { className: "floor-hero-svg", "aria-hidden": "true", inert: "" },
        h(window.FloorScene, { data: ctx.office, day: ctx.day, pending: ctx.office.inbox.length, onOpen: () => ctx.openPage("floor") })),
      h("div", { className: "floor-hero-glaze" }),
      h("div", { className: "floor-hero-cta" },
        h("span", { className: "fh-eyebrow" }, "Virtual office"),
        h("span", { className: "fh-title" }, "See the floor"),
        h("span", { className: "fh-sub" }, "Quick view of desks and pending work."),
        h("span", { className: "fh-go" }, "Open Floor View", h(window.Icon, { name: "arrowRight", size: 14 }))));

    const kpiGrid = h("section", {
      "aria-label": "Key numbers",
      "data-command-primary-signals": "true",
      "data-command-primary-count": "4",
      "data-command-secondary-signals": "true",
      "data-command-secondary-count": "4",
      style: { display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 18 }
    }, D.kpis.map((kpi, index) => {
      const target = KPI_GO[kpi.l] || "";
      return h(KPI, {
        key: kpi.l,
        data: Object.assign({}, kpi, { l: KPI_LABEL[kpi.l] || kpi.l }),
        "data-command-kpi": kpi.l,
        "data-command-kpi-route": target,
        "data-command-kpi-index": String(index),
        "data-command-kpi-drilldown": target ? "true" : "false",
        "data-command-kpi-group": PRIMARY_KPIS.has(kpi.l) ? "primary" : "secondary",
        onClick: target ? () => ctx.setActive(target) : undefined
      });
    }));

    const chartsRow = h("div", { style: { display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16, marginBottom: 18 } },
      h(Card, null,
        h(CardHead, { title: "Tasks completed", sub: "Last 7 days · all employees", icon: "activity", headingLevel: 2, headingId: "command-tasks-title", right: h(Badge, { tone: "green" }, h(window.Icon, { name: "trendUp", size: 11 }), "12%") }),
        h("div", { style: { padding: "16px 18px 6px" } },
          h(window.AreaChart, { data: D.weeklyTasks.data, labels: D.weeklyTasks.labels, height: 230 }))),
      h(Card, null,
        h(CardHead, { title: "Hours saved by department", sub: "This month", icon: "clock", headingLevel: 2, headingId: "command-hours-title" }),
        h("div", { style: { padding: "18px" } },
          h(window.HBars, { items: D.hoursByDept, format: (value) => value + "h" }))));

    const tableCard = h(Card, null,
      h(CardHead, {
        title: "Top active AI employees",
        icon: "users",
        headingLevel: 2,
        right: h(Button, { sm: true, variant: "ghost", iconRight: "chevRight", onClick: () => ctx.setActive("employees") }, "View all")
      }),
      h("div", { className: "command-table-wrap", style: { overflowX: "auto" } },
        h("table", { className: "tbl", "data-command-active-employees-table": "true", "data-command-top-active-employees-table": "true" },
          h("thead", null, h("tr", null, ["AI employee", "Status", "Owner", "Repeat work", "Last task", ""].map((column, index) => h("th", { key: index }, column)))),
          h("tbody", null, D.employees.slice(0, 5).map((employee, index) => {
            const role = ctx.office.roleById && ctx.office.roleById[employee.id];
            const hired = !!(role && role.hired);
            const route = hired ? "employee/" + employee.id : "employees";
            const openRow = () => hired ? ctx.openPage("employee", employee.id) : ctx.setActive("employees");
            const openRowFromKeyboard = (event) => {
              if (event.key !== "Enter" && event.key !== " ") return;
              event.preventDefault();
              openRow();
            };
            return h("tr", {
              key: employee.id,
              className: "row-link",
              role: "button",
              tabIndex: 0,
              "data-command-active-employee-row": "true",
              "data-command-active-employee-role-id": employee.id,
              "data-command-active-employee-hired": hired ? "true" : "false",
              "data-command-active-employee-route": route,
              "data-command-active-employee-keyboard": "true",
              "data-command-top-active-employee-row": employee.id,
              "data-command-top-active-employee-index": String(index),
              "data-command-top-active-employee-route": route,
              "data-command-top-active-employee-keyboard": "true",
              "data-employee-role-id": employee.id,
              onClick: openRow,
              onKeyDown: openRowFromKeyboard
            },
              h("td", null, h("div", { className: "row gap10" },
                h(window.Face, { roleId: employee.id, size: 32, variant: "portrait" }),
                h("div", null,
                  h("div", { style: { fontWeight: 600, fontSize: 13 } }, employee.short),
                  h("div", { style: { fontSize: 11.5, color: "var(--text-faint)" } }, employee.dept)))),
              h("td", null, h(Badge, { status: employee.status, dot: true }, employee.status)),
              h("td", { className: "dim", style: { fontSize: 12.5 } }, employee.owner),
              h("td", null, h("span", { style: { fontSize: 12, fontWeight: 600, color: "var(--text-dim)" } }, /act|auto/i.test(employee.autonomy || "") ? "Approved repeats" : "Approval needed")),
              h("td", { style: { fontSize: 12.5, color: "var(--text-dim)", maxWidth: 200 } }, employee.lastTask),
              h("td", null, h(window.Icon, { name: "chevRight", size: 15, color: "var(--text-faint)" })));
          })))));

    const expansionCard = h(Card, null,
      h(CardHead, { title: "Possible next steps", sub: "What could help next", icon: "sparkle", headingLevel: 2 }),
      h("div", { "data-command-expansion-opportunities": "true", "data-command-expansion-count": String(D.expansion.length), style: { padding: 14, display: "flex", flexDirection: "column", gap: 10 } },
        D.expansion.map((item, index) => {
          const projectionId = item.id || "";
          const route = projectionId ? "roi/" + projectionId : "roi";
          const openProjection = () => ctx.openExpansionProjection ? ctx.openExpansionProjection(item) : ctx.openPage("roi", projectionId);
          const openProjectionFromKeyboard = (event) => {
            if (event.key !== "Enter" && event.key !== " ") return;
            event.preventDefault();
            openProjection();
          };
          return h("div", {
            key: projectionId || index,
            className: "glass-hover",
            role: "button",
            tabIndex: 0,
            "aria-label": "Open value estimate " + item.name,
            "data-command-expansion-card": "true",
            "data-command-expansion-id": projectionId,
            "data-command-expansion-index": String(index),
            "data-command-expansion-route": route,
            "data-command-expansion-confidence": item.conf || "",
            "data-command-expansion-keyboard": "true",
            onClick: openProjection,
            onKeyDown: openProjectionFromKeyboard,
            style: { padding: "13px 14px", borderRadius: 12, border: "1px solid var(--border)", background: "var(--bg-3)", cursor: "pointer" }
          },
            h("div", { className: "row between", style: { marginBottom: 4 } },
              h("div", { className: "row gap8" },
                h("span", { style: { width: 8, height: 8, borderRadius: 3, background: item.color } }),
                h("span", { style: { fontWeight: 600, fontSize: 13.5 } }, item.name)),
              h("span", { style: { fontFamily: "var(--mono)", fontWeight: 700, fontSize: 13, color: "var(--green)" } }, item.lift)),
            h("div", { className: "row between" },
              h("span", { style: { fontSize: 12, color: "var(--text-faint)" } }, item.note),
              h(Badge, { tone: item.conf === "High" ? "green" : "amber" }, "Ready: " + item.conf)));
        }),
        h(Button, { variant: "ghost", iconRight: "arrowRight", "data-command-action": "open-roi", "data-command-route": "roi", style: { justifyContent: "center", marginTop: 2 }, onClick: () => ctx.openPage("roi") }, "See value estimates")));

    const bottomRow = h("div", { style: { display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16 } }, tableCard, expansionCard);

    return h("div", { "data-command-overview": "true" }, isEmptyOffice ? day0Hero : hero, floorHero, kpiGrid, chartsRow, bottomRow);
  }

  window.Screens.command = CommandCenter;
})();
