// AdminPools.jsx — stablecoin liquidity pools. Renée C-2: the OZ table showed
// eight identical "USDC Lending Pool" rows; pool identity is the settlement
// token + the linked credit facility, so each row now reads distinctly.

const AdminPools = ({ pools, state, onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load pools" onRetry={onRetry} />;

  const totalTvl = pools.reduce((s, p) => s + p.tvl, 0);
  const avgApy = (pools.reduce((s, p) => s + p.apy, 0) / pools.length).toFixed(1);
  const avgUtil = (pools.reduce((s, p) => s + p.utilization, 0) / pools.length).toFixed(1);

  const bucket = (u) => u > 80 ? "high" : u >= 50 ? "medium" : "low";
  const filtered = pools.filter(p =>
    (filter === "all" || bucket(p.utilization) === filter) &&
    (q === "" || p.facility.toLowerCase().includes(q.toLowerCase()) || p.token.toLowerCase().includes(q.toLowerCase()))
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <PageHeader eyebrow="Liquidity" title="Stablecoin pools" icon="bank"
        lede="Monitor stablecoin liquidity pools across all credit facilities."
        annot="C-5 sentence case" />

      <HeroStrip
        hero={{ label: "Total value locked", value: fmtMoneyShort(totalTvl), sub: `Across ${pools.length} pools linked to active facilities` }}
        supports={[
          { label: "Average APY", value: `${avgApy}%`, sub: "Weighted by pool" },
          { label: "Avg utilization", value: `${avgUtil}%`, sub: "Across all pools" },
          { label: "High utilization", value: pools.filter(p => p.utilization > 80).length, sub: "Pools above 80%", tone: pools.some(p=>p.utilization>80) ? "warning" : undefined },
        ]}
      />

      <div>
        <SectionHeader eyebrow="Pools" title="All pools" count={filtered.length}
          annot="C-2 token + facility identity"
          action={<SearchBox placeholder="Search by pool or facility…" value={q} onChange={setQ} width={280} />} />

        <div style={{ marginBottom: 16 }}>
          <SegmentControl value={filter} onChange={setFilter} options={[
            { value: "all", label: "All", count: pools.length },
            { value: "high", label: "High (>80%)", count: pools.filter(p => bucket(p.utilization) === "high").length },
            { value: "medium", label: "Medium", count: pools.filter(p => bucket(p.utilization) === "medium").length },
            { value: "low", label: "Low (<50%)", count: pools.filter(p => bucket(p.utilization) === "low").length },
          ]} />
        </div>

        <section className="card" style={{ padding: 0 }}>
          <div className="adm-scroll">
            <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1fr 90px 110px", gap: 14, padding: "10px 20px", background: "var(--bg-alt)", borderBottom: "1px solid var(--border)" }}>
              <Th sortable>Pool</Th><Th align="right" sortable>TVL</Th><Th align="right" sortable>Utilization</Th><Th align="right" sortable>APY</Th><Th align="right">Lenders</Th><Th>Status</Th>
            </div>
            {filtered.length === 0 ? (
              <EmptyState icon="bank" title="No pools match" body="Adjust the filter or search." secondary={{ label: "Show all", onClick: () => { setFilter("all"); setQ(""); } }} />
            ) : filtered.map((p, i) => {
              const tone = p.utilization > 80 ? "var(--gold-70)" : "var(--accent)";
              return (
                <div key={p.id} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1fr 90px 110px", gap: 14, padding: "14px 20px", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span className="chip chip--info" style={{ padding: "1px 7px", fontSize: 11 }}>{p.token}</span>
                      <span style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.facility}</span>
                    </div>
                  </div>
                  <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoneyShort(p.tvl)}</span>
                  <div style={{ textAlign: "right" }}>
                    <div className="tnum" style={{ font: '500 14px "Inter", sans-serif', color: tone }}>{p.utilization.toFixed(1)}%</div>
                    <div style={{ height: 3, background: "var(--black-20)", borderRadius: 2, overflow: "hidden", marginTop: 4 }}><div style={{ width: `${p.utilization}%`, height: "100%", background: tone }} /></div>
                  </div>
                  <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: "var(--success)" }}>{p.apy.toFixed(1)}%</span>
                  <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: "var(--fg)" }}>{p.lenders}</span>
                  <div><AdminStatus status={p.status === "high" ? "high" : "normal"} dot={false} /></div>
                </div>
              );
            })}
          </div>
        </section>
      </div>
    </div>
  );
};

window.AdminPools = AdminPools;
