/* Stratum Leads — Operations Console. Home dashboard + Audit Log pages.
   Home is a pure "what needs attention" overview — it links out to the
   owning page for detail rather than embedding full widgets, so it never
   competes with Inbox/Customers/Lead Ops/Wallet Ops for their own content. */

/* Design-system components — each Babel script has its own scope, so every
   ops-*.jsx file must destructure what it needs from the namespace. */
const { NavItem, IconButton, WalletPill, Tabs, LeadCard, Button, Field, Card, Metric, StatusChip, TierBadge, ContactQuality, ProgressBar, StrataAmount, Checkbox, Switch, Avatar, AvatarStack, SegmentedControl, GateCard, EmptyState, Toast } = window.StratumLeadsDesignSystem_6367ed;

const { I, fmtStrata, getCustomer, TICKET_STATUS_TONE, PRIORITY_TONE, LEADQ_TONE, CATEGORY_LABEL } = window.OpsShared;

function HomePage({ tickets, ledger, leadQueue, auditLog, onNavigate }) {
  const openTickets = tickets.filter((t) => t.status !== "Closed");
  const breached = openTickets.filter((t) => t.slaMinutesLeft !== null && t.slaMinutesLeft < 0);
  const pendingLeads = leadQueue.filter((l) => l.status === "pending");
  const failedPayments = ledger.filter((l) => l.status === "failed");
  const creditedToday = ledger.filter((l) => l.status === "succeeded" && (l.type === "credit" || l.type === "refund") && l.createdAt.startsWith("Today")).
  reduce((sum, l) => sum + l.amount, 0);

  const urgent = [...openTickets].
  sort((a, b) => (a.slaMinutesLeft ?? 9e9) - (b.slaMinutesLeft ?? 9e9)).
  slice(0, 5);

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)" }}>
      <PageHeader eyebrow="Operations Console" title="Operations Console" description="Obvious actions, always traceable. Here's what needs attention right now." />

      <Reveal style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(190px,1fr))", gap: 14, marginBottom: 24 }}>
        <Metric icon={I("inbox")} value={openTickets.length} label="Open tickets" accent="violet" style={{ cursor: "pointer" }} onClick={() => onNavigate("inbox")} />
        <Metric icon={I("alarm-clock")} value={breached.length} label="SLA breached" accent="amber" style={{ cursor: "pointer" }} onClick={() => onNavigate("inbox")} />
        <Metric icon={I("radar")} value={pendingLeads.length} label="Leads pending review" accent="cyan" style={{ cursor: "pointer" }} onClick={() => onNavigate("leadops")} />
        <Metric icon={I("credit-card")} value={failedPayments.length} label="Failed payments" accent="amber" style={{ cursor: "pointer" }} onClick={() => onNavigate("walletops")} />
        <Metric icon={I("coins")} value={fmtStrata(creditedToday)} label="Strata credited today" accent="green" style={{ cursor: "pointer" }} onClick={() => onNavigate("walletops")} />
      </Reveal>

      <Reveal delay={80} style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 20, alignItems: "start" }}>
        <Card title="Needs attention" note="Sorted by SLA — most urgent first" actions={<Button size="sm" variant="secondary" onClick={() => onNavigate("inbox")}>Open Inbox</Button>}>
          {urgent.length === 0 ?
          <EmptyState icon="check-circle-2" title="Nothing urgent" message="All open tickets are within SLA." /> :

          <div style={{ display: "grid" }}>
              {urgent.map((t, i) => {
              const cust = getCustomer(t.customerId);
              return (
                <button key={t.id} onClick={() => onNavigate("inbox", { ticketId: t.id })} style={{ display: "grid", gridTemplateColumns: "1fr auto auto", alignItems: "center", gap: 12, width: "100%", textAlign: "left", padding: "12px 4px", border: "none", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)", background: "transparent", cursor: "pointer" }}>
                    <span style={{ minWidth: 0 }}>
                      <strong style={{ display: "block", fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.subject}</strong>
                      <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{t.id} · {cust?.name}</span>
                    </span>
                    <StatusChip tone={PRIORITY_TONE[t.priority]}>{t.priority}</StatusChip>
                    <SlaBadge minutes={t.slaMinutesLeft} />
                  </button>);

            })}
            </div>
          }
        </Card>

        <Card title="Recent activity" note="Every action taken, logged automatically" actions={<Button size="sm" variant="secondary" onClick={() => onNavigate("auditlog")}>View log</Button>}>
          <div style={{ display: "grid", gap: 2 }}>
            {auditLog.slice(0, 6).map((a, i) =>
            <div key={a.id} style={{ display: "flex", gap: 10, padding: "10px 4px", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)" }}>
                <span style={{ width: 26, height: 26, flexShrink: 0, display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)", fontSize: 10, fontWeight: 800 }}>
                  {a.actor.split(" ").map((w) => w[0]).slice(0, 2).join("")}
                </span>
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: "block", fontSize: 13 }}>{a.action}</span>
                  <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{a.target ? `${a.target} · ` : ""}{a.time}</span>
                </span>
              </div>
            )}
          </div>
        </Card>
      </Reveal>
    </div>);

}

/* ---------------- Audit Log (its own page — full filterable ledger of admin actions) ---------------- */
function extractTicketId(text) {
  const m = /\bTCK-[A-Za-z0-9-]+\b/.exec(text || "");
  return m ? m[0] : null;
}

function AuditLogPage({ auditLog, onOpenTicket, onOpenCustomer }) {
  const [category, setCategory] = React.useState("all");
  const [query, setQuery] = React.useState("");
  React.useEffect(refresh);

  const CATS = [
  { value: "all", label: "All" },
  { value: "ticket", label: "Tickets" },
  { value: "wallet", label: "Wallet" },
  { value: "lead", label: "Leads" },
  { value: "account", label: "Account" },
  { value: "governance", label: "Governance" }];


  const rows = auditLog.filter((a) =>
  (category === "all" || a.category === category) && (
  query.trim() === "" || (a.action + " " + (a.target || "")).toLowerCase().includes(query.trim().toLowerCase()))
  );

  const catMeta = { ticket: ["ticket", "info"], wallet: ["wallet-cards", "violet"], lead: ["radar", "success"], account: ["user-round", "neutral"], governance: ["shield-check", "violet"] };

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)" }}>
      <PageHeader eyebrow="Governance" title="Audit Log" description="Every action taken across Operations Console, logged automatically. Obvious actions, always traceable." />

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, marginBottom: 16, flexWrap: "wrap" }}>
        <Tabs value={category} onChange={setCategory} tabs={CATS} />
        <div style={{ width: 260 }}><Field icon={I("search")} placeholder="Search actions..." value={query} onChange={(e) => setQuery(e.target.value)} /></div>
      </div>

      <Reveal style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)", overflow: "hidden" }}>
        {rows.length === 0 ?
        <EmptyState icon="history" title="No matching activity" message="Try a different filter or search term." /> :

        rows.map((a, i) => {
          const [icon, tone] = catMeta[a.category] || ["circle", "neutral"];
          const ticketId = a.category === "ticket" ? extractTicketId(a.action) : null;
          const onOpen = ticketId ? () => onOpenTicket(ticketId) : a.targetId ? () => onOpenCustomer(a.targetId) : null;
          const Row = onOpen ? "button" : "div";
          return (
            <Row key={a.id} onClick={onOpen || undefined} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", alignItems: "center", gap: 14, padding: "13px 16px", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)", width: "100%", textAlign: "left", border: "none", background: "transparent", font: "inherit", cursor: onOpen ? "pointer" : "default" }}>
                <span style={{ width: 30, height: 30, flexShrink: 0, display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)", fontSize: 10.5, fontWeight: 800 }}>
                  {a.actor.split(" ").map((w) => w[0]).slice(0, 2).join("")}
                </span>
                <span style={{ minWidth: 0 }}>
                  <strong style={{ display: "block", fontSize: 13.5 }}>{a.action}</strong>
                  <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{a.actor}{a.target ? ` · ${a.target}` : ""}</span>
                </span>
                <StatusChip tone={tone}>{a.category}</StatusChip>
                <span style={{ fontSize: 12, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{a.time}</span>
              </Row>);

        })
        }
      </Reveal>
    </div>);

}

Object.assign(window, { OpsHome: { HomePage, AuditLogPage } });
