/* Tasks 6–7 — Inventory + Exceptions */
const { useState: useStateV2, useMemo: useMemoV2 } = React;

/* ── Task 6: Inventory ───────────────────────────────────── */
function InvStatusPill({ status }) {
  const map = { in_stock: "green", assigned: "blue", shipped: "blue", destroyed: "red", vaulted: "amber" };
  return React.createElement("span", { className: "co-pill " + (map[status] || "grey") },
    React.createElement("span", { className: "dot" }), window.CardOps.INV_STATUS[status]);
}

function Inventory({ globalCountry, setCountry, role, loading }) {
  const [status, setStatus] = useStateV2("all");
  const all = window.CardOps.INVENTORY;
  const counts = useMemoV2(() => {
    const c = { in_stock: 0, assigned: 0, shipped: 0, destroyed: 0, vaulted: 0 };
    all.forEach((u) => { c[u.status] = (c[u.status] || 0) + 1; });
    return c;
  }, []);
  const rows = useMemoV2(() => all.filter((u) =>
    (status === "all" || u.status === status) &&
    (globalCountry === "all" || u.country === globalCountry)), [status, globalCountry]);
  const lowStock = counts.in_stock < window.CardOps.LOW_STOCK_THRESHOLD;

  const tiles = [
    { k: "in_stock", tone: "green" }, { k: "assigned", tone: "blue" }, { k: "shipped", tone: "blue" },
    { k: "vaulted", tone: "amber" }, { k: "destroyed", tone: "red" },
  ];

  return React.createElement("div", { className: "co-page" },
    React.createElement("div", { className: "co-page-head" },
      React.createElement("div", null,
        React.createElement("h1", { className: "co-page-title" }, "Inventory"),
        React.createElement("p", { className: "co-page-sub" }, all.length, " physical card units tracked")),
      React.createElement(window.GatedButton, { perm: "edit_inventory", role, variant: "secondary", icon: "plus", onClick: () => {} }, "Receive stock")),

    lowStock && React.createElement("div", { className: "co-banner amber" },
      React.createElement(window.Icon, { name: "alert" }),
      React.createElement("div", null, React.createElement("b", null, "Low stock — ", counts.in_stock, " units"), " remain in stock (threshold ", window.CardOps.LOW_STOCK_THRESHOLD, "). Re-order to avoid activation delays.")),

    React.createElement("div", { style: { display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 12, marginBottom: 18 } },
      tiles.map((t) => React.createElement("button", { key: t.k, className: "co-kpi", style: { minHeight: 92, textAlign: "left" }, onClick: () => setStatus(status === t.k ? "all" : t.k) },
        React.createElement("div", { className: "co-kpi-label" }, window.CardOps.INV_STATUS[t.k]),
        React.createElement("div", { className: "co-kpi-value", style: { fontSize: 26 } }, counts[t.k])))),

    React.createElement("div", { className: "co-filterbar" },
      React.createElement("button", { className: "co-filter-btn" + (status === "all" ? " set" : ""), onClick: () => setStatus("all"), style: status === "all" ? null : {} }, "All statuses"),
      Object.keys(window.CardOps.INV_STATUS).map((s) => React.createElement("button", { key: s, className: "co-filter-btn" + (status === s ? " set" : ""), onClick: () => setStatus(s) }, window.CardOps.INV_STATUS[s]))),

    loading
      ? React.createElement("div", { className: "co-table-wrap" }, React.createElement(window.SkeletonRows, { rows: 8, cols: 5 }))
      : rows.length === 0
        ? React.createElement("div", { className: "co-card" }, React.createElement(window.EmptyState, { icon: "inventory", title: "No units match", sub: "Adjust the status or country filter." }))
        : React.createElement("div", { className: "co-table-wrap" },
            React.createElement("table", { className: "co-table" },
              React.createElement("thead", null, React.createElement("tr", null,
                ["Unit", "Card number", "Status", "Country", "Linked order", "Updated"].map((h) => React.createElement("th", { key: h, className: "no-sort" }, h)))),
              React.createElement("tbody", null,
                rows.map((u) => React.createElement("tr", { key: u.id, style: { cursor: "default" } },
                  React.createElement("td", { className: "co-cell-mono co-cell-strong" }, u.id.toUpperCase()),
                  React.createElement("td", { className: "co-cell-mono co-cell-muted" }, u.full.slice(0, 7), "·· ···· ", u.last4),
                  React.createElement("td", null, React.createElement(InvStatusPill, { status: u.status })),
                  React.createElement("td", { className: "co-cell-muted" }, window.CardOps.flag(u.country), " ", u.country),
                  React.createElement("td", { className: "co-cell-mono co-cell-muted" }, u.order || "—"),
                  React.createElement("td", { className: "co-cell-muted" }, u.updated)))))));
}

/* ── Task 7: Exceptions ──────────────────────────────────── */
function Exceptions({ globalProduct, globalCountry, role, onOpenOrder, loading }) {
  const EXC = window.CardOps.EXC_TYPES;
  const SEV = window.CardOps.SEV;
  const rows = useMemoV2(() => window.CardOps.ORDERS
    .filter((o) => window.CardOps.exceptionStatuses.includes(o.status))
    .filter((o) => globalProduct === "All" || o.product === globalProduct)
    .filter((o) => globalCountry === "all" || o.country === globalCountry)
    .sort((a, b) => (SEV[EXC[b.status].sev] - SEV[EXC[a.status].sev]) || (b.days - a.days)),
    [globalProduct, globalCountry]);

  const sevPill = (sev) => React.createElement("span", { className: "co-pill " + (sev === "critical" ? "red" : (sev === "high" ? "amber" : "blue")) }, sev);

  const quickActions = (o) => {
    const acts = {
      blocked: [["reissue", "rotate", "Reissue"], ["send_reminder", "mail", "Contact"]],
      payment_overdue: [["send_reminder", "send", "Send reminder"], ["block", "ban", "Block"]],
      mismatch: [["start_activation", "camera", "Retake & verify"]],
      undeliverable: [["send_reminder", "map", "Fix address"], ["reissue", "truck", "Re-ship"]],
      returned: [["send_reminder", "map", "Fix address"], ["reissue", "truck", "Re-ship"]],
      lost: [["reissue", "rotate", "Continue reissue"]],
      expiring: [["send_reminder", "send", "Send renewal"]],
    }[o.status] || [["send_reminder", "send", "Contact"]];
    return acts.map(([perm, icon, label]) => React.createElement(window.GatedButton, { key: label, perm, role, variant: "secondary", size: "sm", icon, onClick: () => onOpenOrder(o) }, label));
  };

  return React.createElement("div", { className: "co-page" },
    React.createElement("div", { className: "co-page-head" },
      React.createElement("div", null,
        React.createElement("h1", { className: "co-page-title" }, "Exceptions"),
        React.createElement("p", { className: "co-page-sub" }, rows.length, " open · sorted by severity, then age"))),

    loading
      ? React.createElement("div", { className: "co-card" }, React.createElement(window.SkeletonRows, { rows: 6, cols: 4 }))
      : rows.length === 0
        ? React.createElement("div", { className: "co-card" }, React.createElement(window.EmptyState, { icon: "checkcircle", title: "No open exceptions", sub: "Everything is healthy in this view." }))
        : React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 10 } },
            rows.map((o) => {
              const meta = EXC[o.status];
              const sevColor = meta.sev === "critical" ? "red" : (meta.sev === "high" ? "amber" : "blue");
              return React.createElement("div", { key: o.id, className: "co-card", style: { padding: "14px 16px", display: "flex", alignItems: "center", gap: 14, borderLeft: "3px solid var(--co-" + sevColor + ")" } },
                React.createElement("div", { style: { flex: 1, minWidth: 0 } },
                  React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap" } },
                    sevPill(meta.sev),
                    React.createElement(window.Tag, { product: o.product }),
                    React.createElement("span", { style: { fontWeight: 600, fontSize: 14 } }, meta.label),
                    React.createElement("span", { style: { color: "var(--co-text-3)", fontSize: 13 } }, "· ", o.holder)),
                  React.createElement("div", { style: { fontSize: 12, color: "var(--co-text-3)", marginTop: 4 } },
                    React.createElement("span", { style: { fontFamily: "var(--co-mono)" } }, o.ref), " · ", window.CardOps.COUNTRIES[o.country],
                    " · ", React.createElement("span", { className: o.days >= 6 ? "co-days bad" : (o.days >= 4 ? "co-days warn" : "") }, o.days, " days in state"))),
                React.createElement("div", { style: { display: "flex", gap: 8, flexShrink: 0, flexWrap: "wrap", justifyContent: "flex-end" } },
                  quickActions(o),
                  React.createElement("button", { className: "co-icon-btn", onClick: () => onOpenOrder(o), title: "Open order" }, React.createElement(window.Icon, { name: "chevright" }))));
            })));
}

Object.assign(window, { Inventory, Exceptions });
