// Cases view — real case list, not alerts.

const { useState: useCaseState, useMemo: useCaseMemo } = React;

function CaseStatusPill({ status }) {
  const map = {
    open:       { cls: "pill info",  label: "Open" },
    in_review:  { cls: "pill med",   label: "In review" },
    escalated:  { cls: "pill high",  label: "Escalated" },
    closed:     { cls: "pill low",   label: "Closed" },
  };
  const m = map[status] || { cls: "pill", label: status };
  return <span className={m.cls}>{m.label}</span>;
}

function CasesView({ data, onOpenCase }) {
  const cases = data?.cases || window.CASES_API || [];
  const [statusFilter, setStatusFilter] = useCaseState("all");
  const [sortBy, setSortBy] = useCaseState("opened");

  const filtered = useCaseMemo(() => {
    let r = cases;
    if (statusFilter !== "all") {
      r = r.filter(c => c.status === statusFilter);
    }
    r = [...r].sort((a, b) => {
      if (sortBy === "risk") return b.risk - a.risk;
      if (sortBy === "alerts") return b.alerts - a.alerts;
      return new Date(b.opened) - new Date(a.opened);
    });
    return r;
  }, [cases, statusFilter, sortBy]);

  const counts = useCaseMemo(() => ({
    all: cases.length,
    open: cases.filter(c => c.status === "open").length,
    in_review: cases.filter(c => c.status === "in_review").length,
    escalated: cases.filter(c => c.status === "escalated").length,
    closed: cases.filter(c => c.status === "closed").length,
  }), [cases]);

  return (
    <>
      <div className="tabs">
        <button className={`tab ${statusFilter === "all" ? "active" : ""}`} onClick={() => setStatusFilter("all")}>
          All <span className="tab-count">{counts.all}</span>
        </button>
        <button className={`tab ${statusFilter === "open" ? "active" : ""}`} onClick={() => setStatusFilter("open")}>
          Open <span className="tab-count">{counts.open}</span>
        </button>
        <button className={`tab ${statusFilter === "in_review" ? "active" : ""}`} onClick={() => setStatusFilter("in_review")}>
          In review <span className="tab-count">{counts.in_review}</span>
        </button>
        <button className={`tab ${statusFilter === "escalated" ? "active" : ""}`} onClick={() => setStatusFilter("escalated")}>
          Escalated <span className="tab-count">{counts.escalated}</span>
        </button>
        <button className={`tab ${statusFilter === "closed" ? "active" : ""}`} onClick={() => setStatusFilter("closed")}>
          Closed <span className="tab-count">{counts.closed}</span>
        </button>
        <div style={{ flex: 1 }} />
        <select className="field" value={sortBy} onChange={e => setSortBy(e.target.value)} style={{ width: 150 }}>
          <option value="opened">Sort: Recently opened</option>
          <option value="risk">Sort: Risk score</option>
          <option value="alerts">Sort: Alert count</option>
        </select>
      </div>

      <div style={{ flex: 1, overflow: "auto" }}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Case</th>
              <th>Status</th>
              <th>Priority</th>
              <th>Customer</th>
              <th className="right">Risk</th>
              <th className="right">Alerts</th>
              <th className="right">Amount</th>
              <th>Assignee</th>
              <th>Opened</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(c => (
              <tr key={c.id} onClick={() => onOpenCase?.(c)} style={{ cursor: "pointer" }}>
                <td>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{c.id}</span>
                  <div style={{ fontSize: 12, color: "var(--fg-2)", marginTop: 1 }}>{c.title}</div>
                </td>
                <td><CaseStatusPill status={c.status} /></td>
                <td>
                  <span className={`pill ${c.priority === "medium" ? "med" : c.priority === "critical" ? "high" : c.priority}`}>{c.priority}</span>
                </td>
                <td><span className="mono" style={{ color: "var(--accent)", fontWeight: 500, fontSize: 12 }}>{c.customerId || "—"}</span></td>
                <td className="right mono">{c.risk}</td>
                <td className="right mono">{c.alerts}</td>
                <td className="right mono">{formatAmount(c.amount, "USD")}</td>
                <td>{c.assignee}</td>
                <td className="mono" style={{ fontSize: 11.5, color: "var(--fg-3)" }}>
                  {new Date(c.opened).toLocaleString()}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div style={{
        display: "flex", alignItems: "center",
        padding: "8px 18px",
        borderTop: "1px solid var(--border)",
        background: "var(--bg)",
        fontSize: 11.5, color: "var(--fg-3)",
        gap: 8,
      }}>
        <span>Showing <b style={{ color: "var(--fg)" }}>{filtered.length}</b> of <b style={{ color: "var(--fg)" }}>{cases.length}</b> cases</span>
      </div>
    </>
  );
}

Object.assign(window, { CasesView });
