// FacilityAccess.jsx — Facility Access & Compliance page.
//
// Renée's lens: identity is the anchor (mirror of the Facility Detail prompt).
// This page must answer "across all 12 facilities, where do I stand?".
//
//   · C-4 hierarchy: the *identity* block is the hero. The 4 KPIs sit below
//     in a hairline strip, NOT as 4 large equal-weight cards.
//   · C-5 copy: sentence case; the eligibility rows have plain-English reasons.
//   · C-1: no scaffolding; shell handles.

const EligibilityRow = ({ row, onOpen }) => {
  const eligibility = row.eligibility; // 'eligible' | 'open' | 'partial' | 'not-eligible'
  const map = {
    eligible:      { variant: "eligible",      label: "Eligible",     icon: "check",  iconBg: "var(--green-10)", iconColor: "var(--success)" },
    open:          { variant: "neutral",       label: "Open access",  icon: "check",  iconBg: "var(--blue-10)",  iconColor: "var(--accent)"  },
    partial:       { variant: "at-risk",       label: "Partial",      icon: "alert",  iconBg: "var(--gold-10)",  iconColor: "var(--gold-70)" },
    "not-eligible":{ variant: "not-eligible",  label: "Not eligible", icon: "cross",  iconBg: "var(--red-10)",   iconColor: "var(--danger)"  },
  }[eligibility];

  return (
    <button onClick={() => onOpen && onOpen(row)} className="elig-row" style={{
      all: "unset", cursor: "pointer", width: "100%", boxSizing: "border-box",
      display: "grid",
      gridTemplateColumns: "32px minmax(0, 1.4fr) minmax(0, 2fr) auto",
      gap: 16, padding: "18px 36px 18px 20px",
      borderTop: "1px solid var(--border)",
      alignItems: "center",
      transition: "background var(--motion-fast)",
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"}
    onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
      <span style={{
        width: 24, height: 24, borderRadius: 999,
        background: map.iconBg, color: map.iconColor,
        display: "grid", placeItems: "center",
      }}>
        <Icon name={map.icon} size={12} stroke={2.2}/>
      </span>

      <div style={{ minWidth: 0 }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 8, marginBottom: 2, flexWrap: "wrap",
        }}>
          <span style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>
            {row.name}
          </span>
          <StatusPill variant={map.variant}>{map.label}</StatusPill>
          <span className="chip chip--neutral" style={{ padding: "1px 8px", fontSize: 11 }}>
            {row.region}
          </span>
        </div>
        <div style={{
          font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)",
        }}>
          <span>Settles <span style={{ color: "var(--fg-muted)", fontWeight: 500 }}>{row.settlement.join(", ")}</span></span>
          {"  ·  "}
          <span className="tnum">Rate {row.rate}</span>
          {"  ·  "}
          <span className="tnum">LTV {row.ltv}</span>
        </div>
      </div>

      <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
        {row.requirements.map((req, i) => (
          <span key={i} style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            padding: "2px 8px",
            background: req.met ? "var(--green-10)" : "var(--red-10)",
            color: req.met ? "var(--green-80)" : "var(--red-80)",
            borderRadius: 999,
            font: '500 11px/16px "Inter", sans-serif',
          }}>
            <Icon name={req.met ? "check" : "cross"} size={10} stroke={2.4}/>
            {req.label}
          </span>
        ))}
        {row.requirements.length === 0 && (
          <span style={{
            font: '400 12px/16px "Inter", sans-serif', color: "var(--success)",
            display: "inline-flex", alignItems: "center", gap: 4,
          }}>
            <Icon name="check" size={11} stroke={2.4}/>
            Open to all verified wallets
          </span>
        )}
      </div>

      <span className="btn btn--text" style={{ fontSize: 12 }}>
        View facility <Icon name="arrow" size={12} stroke={1.6}/>
      </span>
    </button>
  );
};

const FacilityAccess = ({ identity, accessKpi, eligibility, onOpenFacility, state = "live", onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't evaluate access" body="The identity registry RPC didn't respond. Your claims are unchanged — this is a read-side issue." 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)" }}>Facility access</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Your eligibility across every credit facility, based on the claims on your Ascend OnchainID.
          </div>
        </div>
        <section className="card" style={{ padding: 0 }}>
          <EmptyState
            icon="shield"
            title="No OnchainID connected"
            body="Connect a wallet with an Ascend-scoped OnchainID to see which facilities you're eligible to borrow against."
            action={{ label: "Connect identity", icon: "shield", onClick: () => {} }}
          />
        </section>
      </div>
    );
  }
  const filtered = eligibility.filter((r) =>
    filter === "all"          ? true :
    filter === "eligible"     ? r.eligibility === "eligible" :
    filter === "open"         ? r.eligibility === "open" :
    filter === "partial"      ? r.eligibility === "partial" :
    filter === "not-eligible" ? r.eligibility === "not-eligible" : true
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      {/* Page header */}
      <div data-annot-note="C-5 sentence case">
        <Eyebrow>Borrow</Eyebrow>
        <h1 style={{
          margin: "6px 0 6px",
          font: '700 32px/36px "Figtree", sans-serif',
          letterSpacing: "-0.015em", color: "var(--fg)",
        }}>Facility access</h1>
        <div style={{
          font: '400 14px/22px "Inter", sans-serif',
          color: "var(--fg-subtle)", maxWidth: 640,
        }}>
          Your eligibility across every credit facility, based on the claims
          attached to your Ascend OnchainID.
        </div>
      </div>

      {/* Identity hero — the page is about this */}
      <section className="card" style={{ padding: 28 }} data-annot-note="C-4 identity-led hero">
        <div className="hero-3col" style={{
          display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 24, alignItems: "center",
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 14,
            background: "var(--green-10)", color: "var(--success)",
            display: "grid", placeItems: "center",
          }}>
            <Icon name="shieldCheck" size={28} stroke={1.5}/>
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{
              display: "flex", alignItems: "center", gap: 10, marginBottom: 4, flexWrap: "wrap",
            }}>
              <StatusPill variant="eligible">OnchainID active</StatusPill>
              <span style={{
                font: '500 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)",
              }}>
                Bound to <span style={{ color: "var(--fg-muted)", fontWeight: 500 }}>{identity.registry}</span>
              </span>
            </div>
            <h2 style={{
              margin: 0, font: '700 24px/30px "Figtree", sans-serif',
              letterSpacing: "-0.012em", color: "var(--fg)",
            }}>You hold an Ascend-scoped OnchainID</h2>
            <div style={{
              marginTop: 6, font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)",
            }}>
              Each credit facility checks the claims on this identity against
              its required claim topics.
            </div>
          </div>
          <button className="btn btn--secondary" type="button">
            <Icon name="external" size={14} stroke={1.6}/>
            View on explorer
          </button>
        </div>

        <div className="info-3col" style={{
          marginTop: 24,
          display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 1,
          background: "var(--border)", borderRadius: 8, overflow: "hidden",
        }}>
          <div style={{ background: "var(--bg-alt)", padding: "14px 16px" }}>
            <div className="stat-label" style={{ fontSize: 11 }}>OnchainID address</div>
            <div style={{ marginTop: 4 }}>
              <MonoAddr full={identity.onchainId} />
            </div>
          </div>
          <div style={{ background: "var(--bg-alt)", padding: "14px 16px" }}>
            <div className="stat-label" style={{ fontSize: 11 }}>Bound registry</div>
            <div style={{
              marginTop: 4, font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)",
            }}>
              {identity.registry}
            </div>
          </div>
          <div style={{ background: "var(--bg-alt)", padding: "14px 16px" }}>
            <div className="stat-label" style={{ fontSize: 11 }}>Claims attached</div>
            <div style={{
              marginTop: 4,
              font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)",
              display: "flex", alignItems: "center", gap: 6,
            }}>
              <span className="tnum">{identity.claimsVerified} verified</span>
              <span style={{ color: "var(--fg-subtle)", fontWeight: 400 }}>·</span>
              <span className="tnum" style={{ color: "var(--fg-subtle)", fontWeight: 400 }}>
                {identity.claims.length} total
              </span>
            </div>
          </div>
        </div>
      </section>

      {/* KPI strip — hairline, supporting */}
      <section className="kpi-strip" style={{
        display: "flex",
        background: "var(--surface)",
        border: "1px solid var(--border)",
        borderRadius: 12,
        flexWrap: "wrap",
      }} data-annot-note="C-4 hairline strip">
        <SupportKPI label="Total facilities"  value={accessKpi.total}        sub="Available on platform" />
        <SupportKPI label="Eligible to borrow" value={accessKpi.eligible}    sub="Ready to open accounts" tone="success" />
        <SupportKPI label="Open access"       value={accessKpi.open}         sub="No identity required" />
        <SupportKPI label="Not eligible"      value={accessKpi.notEligible}  sub="Missing claims or region" tone={accessKpi.notEligible > 0 ? "danger" : undefined} last />
      </section>

      {/* Eligibility list */}
      <section className="card" style={{ padding: 0, overflow: "hidden" }} data-annot-note="C-2 distinguishable rows">
        <div style={{
          padding: "20px 24px 16px",
          display: "flex", justifyContent: "space-between", alignItems: "flex-end",
          gap: 12, flexWrap: "wrap",
        }}>
          <div>
            <Eyebrow>Eligibility</Eyebrow>
            <h2 className="section-heading" style={{ marginTop: 6 }}>
              Per-facility verdict
              <span style={{
                display: "inline-block", marginLeft: 12,
                font: '500 14px/20px "Inter", sans-serif',
                color: "var(--fg-subtle)", verticalAlign: "middle",
              }}>{filtered.length} of {eligibility.length}</span>
            </h2>
          </div>
          <SegmentControl
            value={filter}
            onChange={setFilter}
            options={[
              { value: "all",          label: "All",         count: eligibility.length },
              { value: "eligible",     label: "Eligible",    count: eligibility.filter(r => r.eligibility === "eligible").length },
              { value: "open",         label: "Open",        count: eligibility.filter(r => r.eligibility === "open").length },
              { value: "partial",      label: "Partial",     count: eligibility.filter(r => r.eligibility === "partial").length },
              { value: "not-eligible", label: "Not eligible", count: eligibility.filter(r => r.eligibility === "not-eligible").length },
            ]}
          />
        </div>
        {filtered.map((row, i) => (
          <EligibilityRow key={i} row={row} onOpen={onOpenFacility} />
        ))}
        {filtered.length === 0 && (
          <div style={{ borderTop: "1px solid var(--border)" }}>
            <EmptyState
              icon="search"
              title="No facilities match this filter"
              body="Adjust the segment above to see facilities in another verdict bucket."
              secondary={{ label: "Show all", onClick: () => setFilter("all") }}
            />
          </div>
        )}
      </section>
    </div>
  );
};

Object.assign(window, { FacilityAccess, EligibilityRow });
