/* Sentinel — Queue: role-filtered list of contracts needing a decision
   (Review queue for Head/CEO; My contracts for the RM). */

function queueKpis(role, contracts, decisions) {
  const mine = contracts.filter((c) => role === "rm" ? true : inQueueFor(role, c, decisions));
  const atRisk = mine.filter((c) => c.status !== "cleared" && slaRemainingMin(c.uploadedMs) < 45).length;
  const clearedToday = contracts.filter((c) => c.status === "cleared").length;
  const pendChanges = mine.reduce((s, c) => s + pendingChanges(c, decisions).length, 0);
  if (role === "rm") return [
    { label: "In flight", value: contracts.filter((c) => c.status !== "cleared").length, icon: "file-clock" },
    { label: "Awaiting decision", value: contracts.filter((c) => c.status === "in_review").length, icon: "hourglass", sub: "with reviewers", subTone: "muted" },
    { label: "Processed today", value: clearedToday, icon: "check-circle-2", sub: "all within SLA", subTone: "success" },
    { label: "Avg turnaround", value: "2.4h", icon: "timer", sub: "target 4h", subTone: "success" },
  ];
  if (role === "ceo") return [
    { label: "High-risk awaiting you", value: mine.length, icon: "shield-alert", accent: "var(--status-danger)", sub: atRisk ? atRisk + " near SLA" : "on track", subTone: atRisk ? "warning" : "success" },
    { label: "High-risk changes", value: pendChanges, icon: "gavel" },
    { label: "CEO touch rate", value: "18%", icon: "percent", sub: "of all contracts", subTone: "muted" },
    { label: "Avg time to decide", value: "1.1h", icon: "timer", sub: "high-risk items", subTone: "success" },
  ];
  return [
    { label: "Awaiting your decision", value: mine.length, icon: "list-checks", accent: "var(--ec-primary)" },
    { label: "Changes pending", value: pendChanges, icon: "git-pull-request-arrow" },
    { label: "SLA at risk", value: atRisk, icon: "alarm-clock", accent: atRisk ? "var(--status-warning)" : undefined, sub: atRisk ? "act soon" : "all healthy", subTone: atRisk ? "warning" : "success" },
    { label: "Processed today", value: clearedToday, icon: "check-circle-2", sub: "within SLA", subTone: "success" },
  ];
}

function RiskMini({ risk }) {
  const ctx = React.useContext(SentinelCtx);
  if (!risk) return <span style={{ color: "var(--content-faint)", fontSize: 13 }}>—</span>;
  return <RiskBadge risk={risk} style={ctx.riskStyle} size="sm" />;
}

function ContractQueue({ role, contracts, decisions, search, onOpen }) {
  const kpis = queueKpis(role, contracts, decisions);
  const [filter, setFilter] = React.useState("Active");
  const isRM = role === "rm";

  let rows = contracts.filter((c) => isRM ? true : inQueueFor(role, c, decisions));
  // include cleared in RM view & when filter requests
  rows = rows.filter((c) => {
    const q = (search || "").trim().toLowerCase();
    const okSearch = !q || [c.id, PROVIDERS[c.provider].name, c.type].join(" ").toLowerCase().includes(q);
    let okFilter = true;
    if (filter === "Active") okFilter = c.status !== "cleared";
    else if (filter === "Processed") okFilter = c.status === "cleared";
    else if (filter === "SLA at risk") okFilter = c.status !== "cleared" && slaRemainingMin(c.uploadedMs) < 45;
    return okSearch && okFilter;
  });
  // sort: breached/at-risk first, then by remaining SLA
  rows = rows.slice().sort((a, b) => {
    if (a.status === "cleared" && b.status !== "cleared") return 1;
    if (b.status === "cleared" && a.status !== "cleared") return -1;
    return slaRemainingMin(a.uploadedMs) - slaRemainingMin(b.uploadedMs);
  });

  const filters = isRM ? ["Active", "Processed", "All"] : ["Active", "SLA at risk", "Processed"];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: "flex", gap: 14, marginBottom: 20 }}>
        {kpis.map((k, i) => <KpiCard key={i} {...k} />)}
      </div>

      <div style={{ display: "flex", gap: 8, marginBottom: 14, alignItems: "center" }}>
        {filters.map((f) => {
          const active = filter === f;
          return (
            <button key={f} onClick={() => setFilter(f)} style={{ fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 500, padding: "6px 13px",
              borderRadius: "var(--radius-full)", cursor: "pointer", border: `1px solid ${active ? "var(--ec-primary)" : "var(--border-base)"}`,
              background: active ? "var(--green-50)" : "var(--bg-surface)", color: active ? "var(--green-800)" : "var(--content-base)" }}>{f === "All" ? "All" : f}</button>
          );
        })}
        <div style={{ marginLeft: "auto", fontSize: 13, color: "var(--content-muted)" }}>{rows.length} contract{rows.length !== 1 ? "s" : ""}</div>
      </div>

      <Card style={{ overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
          <thead>
            <tr style={{ background: "var(--bg-sunken)" }}>
              {["Contract", "Provider", "Round", isRM ? "Routed to" : "Top risk", "Pending", "SLA", "Status"].map((h, i) => (
                <th key={h} style={{ textAlign: "left", padding: "11px 16px", fontSize: 11, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase",
                  color: "var(--content-muted)", borderBottom: "1px solid var(--border-base)", whiteSpace: "nowrap" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((c) => {
              const prov = PROVIDERS[c.provider];
              const hr = highestRisk(c, decisions);
              const pend = pendingChanges(c, decisions).length;
              const cleared = c.status === "cleared";
              const classifying = c.status === "classifying";
              const routeLabel = hr ? RISK[hr].routeLabel : "—";
              return (
                <tr key={c.id} onClick={() => !classifying && onOpen(c.id)} style={{ cursor: classifying ? "default" : "pointer" }}
                  onMouseEnter={(e) => { if (!classifying) e.currentTarget.style.background = "var(--bg-sunken)"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}>
                  <td style={{ padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)", whiteSpace: "nowrap" }}>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 500, color: "var(--content-strong)" }}>{c.id}</div>
                    <div style={{ fontSize: 12.5, color: "var(--content-muted)" }}>{c.type}</div>
                  </td>
                  <td style={{ padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                      <Avatar name={prov.name} size={28} tone={prov.tone} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ color: "var(--content-strong)", whiteSpace: "nowrap" }}>{prov.name}</div>
                        <div style={{ fontSize: 12.5, color: "var(--content-muted)" }}>{prov.type}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)", color: "var(--content-base)", fontFamily: "var(--font-mono)", fontSize: 13 }}>R{c.round}</td>
                  <td style={{ padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
                    {isRM ? <span style={{ fontSize: 13, color: "var(--content-base)" }}>{routeLabel}</span> : <RiskMini risk={hr} />}
                  </td>
                  <td style={{ padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)", color: "var(--content-strong)", fontFamily: "var(--font-mono)", fontSize: 13 }}>
                    {classifying ? "—" : cleared ? "0" : pend}
                  </td>
                  <td style={{ padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
                    {cleared ? <span style={{ fontSize: 13, color: "var(--status-success)", fontWeight: 500, fontFamily: "var(--font-mono)" }}>{(c.clearedMin / 60).toFixed(1)}h · ok</span>
                      : classifying ? <span style={{ fontSize: 13, color: "var(--content-muted)" }}>—</span>
                      : <SlaPill uploadedMs={c.uploadedMs} size="sm" />}
                  </td>
                  <td style={{ padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
                    {cleared ? <StatusBadge tone="neutral">Processed</StatusBadge>
                      : classifying ? <StatusBadge tone="progress">Classifying…</StatusBadge>
                      : <StatusBadge tone="info">In review</StatusBadge>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {rows.length === 0 && (
          <div style={{ padding: 48, textAlign: "center", color: "var(--content-muted)" }}>
            <Icon name="inbox" size={28} style={{ color: "var(--content-faint)", marginBottom: 8 }} />
            <div style={{ fontSize: 14 }}>Nothing here right now.{role === "ceo" ? " No contract has a pending high-risk item." : ""}</div>
          </div>
        )}
      </Card>
      <div style={{ marginTop: 12, fontSize: 13, color: "var(--content-faint)", display: "flex", alignItems: "center", gap: 6 }}>
        <Icon name="mouse-pointer-click" size={13} /> Open a contract to review every change in the console.
      </div>
    </div>
  );
}

Object.assign(window, { ContractQueue, RiskMini });
