// FacilitiesList.jsx — Credit Facilities list page.
//
// Addresses Renée:
//   · C-1: no scaffolding (shell handles).
//   · C-2 repeated labels: each facility has a distinguishing name + tranche;
//     "USDC Core Facility" appears once, not six times.
//   · C-4 hierarchy: KPI strip is hairline + smaller than Portfolio's hero;
//     the page is *about* the cards, so they get the visual weight.
//   · C-5 copy: page title is "Credit facilities" (sentence case, no
//     "Discover" marketing verb); subtitle is informational.
//
// Cards are 3-per-row at desktop, with a clear eligibility verdict and a
// status pill, and a single primary action (Open).

const FacilityCard = ({ facility, onOpen }) => {
  const eligibilityVariant = facility.eligibility === "eligible" ? "eligible" :
                             facility.eligibility === "open"     ? "neutral"  :
                             facility.eligibility === "partial"  ? "at-risk"  :
                                                                    "not-eligible";
  const eligibilityLabel  =  facility.eligibility === "eligible" ? "Eligible" :
                             facility.eligibility === "open"     ? "Open access" :
                             facility.eligibility === "partial"  ? "Partial" :
                                                                    "Not eligible";
  const dim = facility.eligibility === "not-eligible";

  return (
    <button onClick={() => onOpen(facility)} style={{
      all: "unset", cursor: "pointer",
      display: "flex", flexDirection: "column", gap: 14,
      padding: 20,
      background: "var(--surface)",
      border: "1px solid var(--border)",
      borderRadius: 12,
      transition: "border-color var(--motion-fast), transform var(--motion-fast)",
      opacity: dim ? 0.75 : 1,
    }}
    onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--border-strong)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--border)"; }}>

      {/* Header row */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{
            font: '600 16px/22px "Figtree", sans-serif',
            letterSpacing: "-0.005em", color: "var(--fg)",
            display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap",
          }}>
            {facility.name}
            <StatusPill variant={facility.statusVariant}>{facility.statusLabel}</StatusPill>
          </div>
          <div style={{
            font: '400 12px/16px "Inter", sans-serif',
            color: "var(--fg-subtle)", marginTop: 3,
          }}>
            {facility.tranche} · {facility.region}
          </div>
        </div>
        <StatusPill variant={eligibilityVariant}>{eligibilityLabel}</StatusPill>
      </div>

      {/* Rate / LTV / Utilization */}
      <div style={{
        display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12,
        paddingTop: 14, borderTop: "1px solid var(--border)",
      }}>
        <div>
          <div className="stat-label" style={{ fontSize: 11 }}>Interest rate</div>
          <div className="tnum" style={{
            font: '600 18px/24px "Inter", sans-serif', color: "var(--fg)", marginTop: 2,
            letterSpacing: "-0.005em",
          }}>{facility.rate}</div>
        </div>
        <div>
          <div className="stat-label" style={{ fontSize: 11 }}>Max LTV</div>
          <div className="tnum" style={{
            font: '600 18px/24px "Inter", sans-serif', color: "var(--fg)", marginTop: 2,
            letterSpacing: "-0.005em",
          }}>{facility.maxLtv}</div>
        </div>
        <div>
          <div className="stat-label" style={{ fontSize: 11 }}>Utilization</div>
          <div className="tnum" style={{
            font: '600 18px/24px "Inter", sans-serif', color: "var(--fg)", marginTop: 2,
            letterSpacing: "-0.005em",
          }}>{facility.utilization}</div>
        </div>
      </div>

      {/* Utilization bar */}
      <div style={{
        height: 3, background: "var(--black-20)", borderRadius: 2, overflow: "hidden",
      }}>
        <div style={{
          width: facility.utilization, height: "100%",
          background: "var(--accent)", borderRadius: 2,
        }} />
      </div>

      {/* Token chips */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
        <span style={{ font: '400 11px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginRight: 4 }}>
          Settles
        </span>
        {facility.settlement.map((t, i) => (
          <span key={i} className="chip chip--info" style={{ padding: "1px 8px", fontSize: 11 }}>{t.ticker || t}</span>
        ))}
        <span style={{ font: '400 11px/16px "Inter", sans-serif', color: "var(--fg-subtle)", margin: "0 4px" }}>
          ·
        </span>
        <span style={{ font: '400 11px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginRight: 4 }}>
          Collateral
        </span>
        {facility.collateral.map((t, i) => (
          <span key={i} className="chip chip--neutral" style={{ padding: "1px 8px", fontSize: 11 }}>{t.ticker || t}</span>
        ))}
      </div>

      {/* Ineligibility reason if any */}
      {facility.notEligibleReason && (
        <div style={{
          display: "flex", alignItems: "center", gap: 6,
          padding: "8px 10px",
          background: "var(--red-10)", borderRadius: 6,
          font: '400 12px/16px "Inter", sans-serif',
          color: "var(--red-80)",
        }}>
          <Icon name="info" size={12} stroke={1.7}/>
          {facility.notEligibleReason}
        </div>
      )}
    </button>
  );
};

const FacilitiesList = ({ data, onOpenFacility, state = "live", onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  if (state === "loading") return <PageSkeleton shape="list" />;
  if (state === "error")   return <PageError title="Couldn't load facilities" body="The facility registry didn't respond. Try again in a moment." onRetry={onRetry} />;
  if (state === "empty") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
        <div>
          <Eyebrow>Borrow</Eyebrow>
          <h1 style={{ margin: "6px 0 6px", font: '700 32px/36px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>Credit facilities</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Permissioned credit pools. Each facility defines its own compliance policy.
          </div>
        </div>
        <section className="card" style={{ padding: 0 }}>
          <EmptyState
            icon="facility"
            title="No facilities available"
            body="There are no credit facilities open on this network yet. Check back once issuers deploy."
            secondary={{ label: "Switch network", onClick: () => {} }}
          />
        </section>
      </div>
    );
  }
  const filtered = data.facilities.filter((f) =>
    filter === "all"      ? true :
    filter === "eligible" ? f.eligibility === "eligible" || f.eligibility === "open" :
    filter === "active"   ? f.statusVariant === "active" :
    filter === "paused"   ? f.statusVariant === "paused" : true
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <div data-annot-note="C-5 sentence case · was 'Discover Credit Facilities'">
        <Eyebrow>Borrow</Eyebrow>
        <h1 style={{
          margin: "6px 0 6px",
          font: '700 32px/36px "Figtree", sans-serif',
          letterSpacing: "-0.015em", color: "var(--fg)",
        }}>Credit facilities</h1>
        <div style={{
          font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)", maxWidth: 640,
        }}>
          Permissioned credit pools. Each facility defines its own compliance
          policy, collateral set, and settlement tokens.
        </div>
      </div>

      {/* KPI strip — hairline, supports the cards rather than competing */}
      <section className="kpi-strip" style={{
        display: "flex",
        background: "var(--surface)",
        border: "1px solid var(--border)",
        borderRadius: 12,
        flexWrap: "wrap",
      }} data-annot-note="C-4 reduced to hairline strip">
        <SupportKPI label="Total facilities" value={data.kpi.total}      sub="10 active · 2 paused" />
        <SupportKPI label="Your access"      value={data.kpi.access}     sub="Eligible to borrow"     tone="success" />
        <SupportKPI label="Avg interest rate" value={data.kpi.avgRate}   sub="Across active facilities" />
        <SupportKPI label="Avg utilization"  value={data.kpi.avgUtil}    sub="Pool deployment"        last />
      </section>

      {/* Filter row */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        gap: 12, flexWrap: "wrap",
      }}>
        <SegmentControl
          value={filter}
          onChange={setFilter}
          options={[
            { value: "all",      label: "All",         count: data.facilities.length },
            { value: "eligible", label: "Eligible",    count: data.facilities.filter(f => f.eligibility === "eligible" || f.eligibility === "open").length },
            { value: "active",   label: "Active",      count: data.facilities.filter(f => f.statusVariant === "active").length },
            { value: "paused",   label: "Paused",      count: data.facilities.filter(f => f.statusVariant === "paused").length },
          ]}
        />
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "0 12px", height: 32,
          border: "1px solid var(--border-strong)", borderRadius: 8,
          background: "var(--surface)",
          font: '400 13px "Inter", sans-serif', color: "var(--fg-subtle)",
          width: 280, maxWidth: "100%",
        }}>
          <Icon name="search" size={14} stroke={1.6}/>
          <span>Search facilities by name or token…</span>
        </div>
      </div>

      {/* Cards grid */}
      <section data-annot-note="C-2 distinguishable labels">
        {filtered.length === 0 ? (
          <section className="card" style={{ padding: 0 }}>
            <EmptyState
              icon="search"
              title="No facilities match this filter"
              body="Adjust the segment above to see facilities in another bucket."
              secondary={{ label: "Show all", onClick: () => setFilter("all") }}
            />
          </section>
        ) : (
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))",
            gap: 16,
          }}>
            {filtered.map((f) => (
              <FacilityCard key={f.id} facility={f} onOpen={onOpenFacility} />
            ))}
          </div>
        )}
      </section>
    </div>
  );
};

Object.assign(window, { FacilitiesList, FacilityCard });
