// Portfolio.jsx — Client Portfolio dashboard, redesign pass.
//
// Addresses, from Renée's review:
//   · C-1 scaffolding: no "For Internal Use Only" pill (lives on AppShell);
//     no floating mock-data banner (replaced by thin bottom strip on the shell).
//   · C-2 repeated labels: each lending pool now reads with a distinguishing
//     facility name + tranche/term + native token (no more 6× "USDC Lending
//     Pool"); margin-account cards prefix with `ma-NNNN · facility`.
//   · C-4 hierarchy: ONE hero KPI (Net position) carries the weight of the
//     dashboard; supporting KPIs sit as a hairline strip below. Sub-sections
//     each get a clear eyebrow + section heading + count. Cards lose
//     equal-weight numbers in favor of label/value pairs.
//   · C-5 copy: sentence case, declarative voice. Min HF gets a context line
//     ("Across 3 at-risk accounts \u00b7 1.39 closest to liquidation") so the
//     red number is never naked.
//   · C-6 data coherence: Net position is the *single* source of truth and is
//     defined in plain English directly under the value.

// ===========================================================================
// Hero KPI — the one number the page is about
// ===========================================================================

const HeroKPI = ({ label, value, sub, trend }) => (
  <div style={{
    flex: "2 1 320px", minWidth: 0,
    padding: "24px 28px",
    background: "var(--surface)",
    borderRadius: 12,
    border: "1px solid var(--border)",
    display: "flex", flexDirection: "column", gap: 8,
  }} data-annot-note="C-4 hero KPI">
    <Eyebrow>{label}</Eyebrow>
    <div className="tnum" style={{
      font: '700 48px/52px "Figtree", sans-serif',
      letterSpacing: "-0.018em", color: "var(--fg)",
    }}>{value}</div>
    <div style={{
      font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)",
      display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap",
    }}>
      {sub}
      {trend && (
        <span className="tnum" style={{
          color: trend.startsWith("+") ? "var(--success)" : trend.startsWith("-") ? "var(--danger)" : "var(--fg-subtle)",
          fontWeight: 500,
        }}>{trend}</span>
      )}
    </div>
  </div>
);

// Supporting KPI — sits in the hairline strip
const SupportKPI = ({ label, value, sub, tone, last }) => (
  <div className="support-kpi" style={{
    minWidth: 0,
    padding: "20px 24px",
    background: "var(--surface)",
  }}>
    <div className="stat-label" style={{ minHeight: "32px" }}>{label}</div>
    <div className="tnum" style={{
      font: '600 20px/26px "Inter", sans-serif',
      color: tone === "danger" ? "var(--danger)" :
             tone === "warning" ? "var(--gold-70)" :
             tone === "success" ? "var(--success)" : "var(--fg)",
      letterSpacing: "-0.01em",
      marginTop: 4,
    }} title={typeof value === "string" ? value : undefined}>{value}</div>
    {sub && (
      <div className="kpi-sub" title={sub} style={{
        font: '400 12px/16px "Inter", sans-serif',
        color: "var(--fg-subtle)", marginTop: 4,
      }}>{sub}</div>
    )}
  </div>
);

// ===========================================================================
// Wallet balances — compact strip, no longer a hero card
// ===========================================================================

const WalletStrip = ({ balances, onViewAll }) => (
  <section className="card" style={{ padding: "18px 24px" }} data-annot-note="C-4 reduced weight">
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <Icon name="accounts" size={14} stroke={1.5} style={{ color: "var(--fg-muted)" }} />
        <Eyebrow>Wallet balances</Eyebrow>
        <span className="tnum" style={{
          font: '500 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)",
        }}>{balances.length} tokens</span>
      </div>
      <button className="btn btn--text" type="button" onClick={onViewAll}>
        View all <Icon name="arrow" size={12} stroke={1.6}/>
      </button>
    </div>
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
      {balances.map((b, i) => (
        <span key={i} style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "5px 10px", background: "var(--bg-alt)",
          borderRadius: 999,
          font: '500 12px/16px "Inter", sans-serif', color: "var(--fg)",
        }}>
          <span style={{ fontWeight: 600 }}>{b.ticker}</span>
          <span className="tnum" style={{ color: "var(--fg-subtle)", fontWeight: 400 }}>
            {b.balance}
          </span>
        </span>
      ))}
    </div>
  </section>
);

// ===========================================================================
// Lending positions — distinguishable cards, no repeated labels
// ===========================================================================

const LendingPositionCard = ({ pos }) => (
  <div style={{
    padding: 20,
    background: "var(--surface)",
    border: "1px solid var(--border)",
    borderRadius: 12,
    display: "flex", flexDirection: "column", gap: 12,
    transition: "border-color var(--motion-fast)",
    cursor: "pointer",
  }}
  onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--border-strong)"}
  onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--border)"}>
    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8 }}>
      <div style={{ minWidth: 0 }}>
        <div style={{
          font: '600 15px/20px "Figtree", sans-serif',
          letterSpacing: "-0.005em", color: "var(--fg)",
        }}>{pos.name}</div>
        <div style={{
          font: '400 12px/16px "Inter", sans-serif',
          color: "var(--fg-subtle)", marginTop: 2,
        }}>
          {pos.tranche} · Settles {pos.settles}
        </div>
      </div>
      <span className="pill pill--healthy" style={{ padding: "2px 8px" }}>
        <span className="tnum">{pos.apy}</span> APY
      </span>
    </div>

    <div style={{
      display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12,
      paddingTop: 12, borderTop: "1px solid var(--border)",
    }}>
      <div>
        <div className="stat-label" style={{ fontSize: 11 }}>Current value</div>
        <div className="tnum" style={{
          font: '600 17px/22px "Inter", sans-serif', color: "var(--fg)", marginTop: 2,
        }}>{pos.currentValue}</div>
      </div>
      <div>
        <div className="stat-label" style={{ fontSize: 11 }}>Earned yield</div>
        <div className="tnum" style={{
          font: '600 17px/22px "Inter", sans-serif', color: "var(--success)", marginTop: 2,
        }}>+{pos.earnedYield}</div>
      </div>
    </div>

    <div style={{
      display: "flex", justifyContent: "space-between",
      font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)",
    }}>
      <span>Deposited <span className="tnum" style={{ color: "var(--fg-muted)", fontWeight: 500 }}>{pos.deposited}</span></span>
      <span>TVL <span className="tnum" style={{ color: "var(--fg-muted)", fontWeight: 500 }}>{pos.tvl}</span></span>
    </div>
  </div>
);

const LendingPositions = ({ positions }) => (
  <section data-annot-note="C-2 distinguishable labels · C-4 hierarchy">
    <SectionHeader
      eyebrow="Lend"
      title="Your lending positions"
      count={positions.length}
      action={{ label: "Search positions", icon: "search", onClick: () => {} }}
    />
    <div style={{
      display: "grid",
      gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))",
      gap: 12,
    }}>
      {positions.map((p, i) => (
        <LendingPositionCard key={i} pos={p} />
      ))}
    </div>
  </section>
);

// ===========================================================================
// Facilities with active accounts — table, not card grid
// (the OZ design used a card grid with 6 facilities at once which over-weights
// this section; a compact table reads faster and frees breathing room)
// ===========================================================================

const FacilitiesWithAccounts = ({ rows, onOpenFacility }) => (
  <section className="card" style={{ padding: 0 }} data-annot-note="C-4 hierarchy \u00b7 was 6-card grid \u2192 row table">
    <div style={{ padding: "20px 24px 16px", display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 12, flexWrap: "wrap" }}>
      <div>
        <Eyebrow>Borrow</Eyebrow>
        <h2 className="section-heading" style={{ marginTop: 6 }}>
          Facilities you're active in
          <span style={{
            display: "inline-block", marginLeft: 12,
            font: '500 14px/20px "Inter", sans-serif',
            color: "var(--fg-subtle)", verticalAlign: "middle",
          }}>{rows.length}</span>
        </h2>
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        <SegmentControl
          value="all"
          options={[
            { value: "all",       label: "All", count: rows.length },
            { value: "healthy",   label: "Healthy", count: rows.filter(r => r.status === "healthy").length },
            { value: "at-risk",   label: "At risk", count: rows.filter(r => r.status === "at-risk").length },
            { value: "default",   label: "Liquidated", count: rows.filter(r => r.status === "default").length },
          ]}
          onChange={() => {}}
        />
      </div>
    </div>

    <div className="fac-scroll">
    <div className="fac-head" style={{
      display: "grid",
      gridTemplateColumns: "minmax(220px, 2fr) 1fr 1fr 1fr 1fr 120px",
      padding: "8px 24px",
      borderTop: "1px solid var(--border)",
      borderBottom: "1px solid var(--border)",
      background: "var(--bg-alt)",
      font: '500 11px/16px "Inter", sans-serif',
      letterSpacing: "0.04em", textTransform: "uppercase",
      color: "var(--fg-subtle)",
      gap: 12,
    }}>
      <span>Facility</span>
      <span style={{ textAlign: "right" }}>Collateral</span>
      <span style={{ textAlign: "right" }}>Borrowed</span>
      <span style={{ textAlign: "right" }}>Health</span>
      <span style={{ textAlign: "right" }}>Rate</span>
      <span></span>
    </div>

    {rows.map((r, i) => {
      const hf = parseFloat(r.hf);
      const hfColor = r.status === "default" || hf < 1.2 ? "var(--danger)" :
                      r.status === "at-risk" || hf < 1.5 ? "var(--gold-70)" :
                                                            "var(--success)";
      const accent = r.status === "at-risk" ? "var(--gold-60)" :
                     r.status === "default" ? "var(--danger)" : "transparent";
      return (
        <button key={i} onClick={() => onOpenFacility && onOpenFacility(r)} className="fac-row" style={{
          all: "unset", cursor: "pointer",
          display: "grid",
          gridTemplateColumns: "minmax(220px, 2fr) 1fr 1fr 1fr 1fr 120px",
          padding: "16px 24px",
          borderTop: i === 0 ? "none" : "1px solid var(--border)",
          borderLeft: `3px solid ${accent}`,
          gap: 12, alignItems: "center",
          transition: "background var(--motion-fast)",
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"}
        onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2 }}>
              <span style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>
                {r.name}
              </span>
              <StatusPill variant={r.status === "default" ? "frozen" : r.status}>{r.statusLabel}</StatusPill>
            </div>
            <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
              {r.collateralTokens.join(", ")}
            </div>
          </div>
          <div className="tnum" style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)", textAlign: "right" }}>
            {r.collateral}
          </div>
          <div className="tnum" style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)", textAlign: "right" }}>
            {r.borrowed}
          </div>
          <div className="tnum" style={{
            font: '600 14px/20px "Inter", sans-serif', color: hfColor, textAlign: "right",
          }}>
            {r.hf}
          </div>
          <div className="tnum" style={{
            font: '500 14px/20px "Inter", sans-serif', color: "var(--accent)", textAlign: "right",
          }}>
            {r.rate}
          </div>
          <div style={{ textAlign: "right", color: "var(--fg-faint)" }}>
            <Icon name="chevron" size={14} />
          </div>
        </button>
      );
    })}
    </div>
  </section>
);

// ===========================================================================
// Shared section header — eyebrow + heading + count + optional action
// ===========================================================================

const SectionHeader = ({ eyebrow, title, count, action }) => (
  <div style={{
    display: "flex", justifyContent: "space-between", alignItems: "flex-end",
    gap: 12, marginBottom: 16, flexWrap: "wrap",
  }}>
    <div>
      <Eyebrow>{eyebrow}</Eyebrow>
      <h2 className="section-heading" style={{ marginTop: 6 }}>
        {title}
        {count !== undefined && (
          <span style={{
            display: "inline-block", marginLeft: 12,
            font: '500 14px/20px "Inter", sans-serif',
            color: "var(--fg-subtle)", verticalAlign: "middle",
          }}>{count}</span>
        )}
      </h2>
    </div>
    {action && (
      <button className="btn btn--text" type="button" onClick={action.onClick}>
        {action.icon && <Icon name={action.icon} size={13} stroke={1.6}/>}
        {action.label}
      </button>
    )}
  </div>
);

// ===========================================================================
// Segment control — tab pill row
// ===========================================================================

const SegmentControl = ({ value, options, onChange }) => (
  <div style={{
    display: "inline-flex", padding: 3,
    background: "var(--bg-alt)", borderRadius: 999,
    border: "1px solid var(--border)",
  }}>
    {options.map((o) => {
      const active = o.value === value;
      return (
        <button key={o.value} type="button" onClick={() => onChange(o.value)} style={{
          all: "unset", cursor: "pointer",
          display: "inline-flex", alignItems: "center", gap: 6,
          padding: "4px 12px", borderRadius: 999,
          font: '500 12px/16px "Inter", sans-serif',
          color: active ? "var(--fg)" : "var(--fg-subtle)",
          background: active ? "var(--surface)" : "transparent",
          boxShadow: active ? "0 1px 2px rgba(0,0,0,0.04)" : "none",
          transition: "background var(--motion-fast), color var(--motion-fast)",
        }}>
          {o.label}
          {o.count !== undefined && (
            <span className="tnum" style={{
              color: "var(--fg-faint)", fontWeight: 400,
            }}>{o.count}</span>
          )}
        </button>
      );
    })}
  </div>
);

// ===========================================================================
// Portfolio page — composes everything
// ===========================================================================

const Portfolio = ({ data, onOpenFacility, state = "live", onRetry }) => {
  if (state === "loading") return <PageSkeleton shape="dashboard" />;
  if (state === "error")   return <PageError title="Couldn't load your portfolio" onRetry={onRetry} />;
  if (state === "empty") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
        <div>
          <Eyebrow>Overview</Eyebrow>
          <h1 style={{
            margin: "6px 0 6px",
            font: '700 32px/36px "Figtree", sans-serif',
            letterSpacing: "-0.015em", color: "var(--fg)",
          }}>Portfolio</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Margin accounts and lending positions across connected facilities.
          </div>
        </div>
        <section className="card" style={{ padding: 0 }}>
          <EmptyState
            icon="grid"
            title="Nothing here yet"
            body="Once you borrow against a facility or supply to a lending pool, your positions and balances will appear here."
            action={{ label: "Browse credit facilities", icon: "facility", onClick: () => onOpenFacility && onOpenFacility(null) }}
            secondary={{ label: "Learn how Ascend works", onClick: () => {} }}
          />
        </section>
      </div>
    );
  }

  // Min Health Factor gets a context line so it's never a naked red number (C-6)
  const minHF = data.minHF;
  const minHFTone = parseFloat(minHF.value) < 1.2 ? "danger" :
                    parseFloat(minHF.value) < 1.5 ? "warning" : "success";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      {/* Page header */}
      <div data-annot-note="C-5 sentence case">
        <Eyebrow>Overview</Eyebrow>
        <h1 style={{
          margin: "6px 0 6px",
          font: '700 32px/36px "Figtree", sans-serif',
          letterSpacing: "-0.015em", color: "var(--fg)",
        }}>Portfolio</h1>
        <div style={{
          font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)",
        }}>
          Margin accounts and lending positions across connected facilities.
        </div>
      </div>

      {/* Hero KPI + supporting strip */}
      <section style={{
        display: "flex", gap: 16, flexWrap: "wrap",
      }} data-annot-note="C-4 hierarchy · was 5 equal-weight cards">
        <HeroKPI
          label="Net position"
          value={data.netPosition.value}
          sub={data.netPosition.sub}
          trend={data.netPosition.trend}
        />
        <div className="kpi-strip" style={{
          flex: "3 1 480px", minWidth: 0,
          background: "var(--surface)",
          border: "1px solid var(--border)",
          borderRadius: 12,
          display: "flex", flexWrap: "wrap",
        }}>
          <SupportKPI label="Total collateral" value={data.totalCollateral} sub="Across 11 positions · $19,589,392" />
          <SupportKPI label="Total borrowed"   value={data.totalBorrowed}   sub="Across 3 facilities · $12,052,376" />
          <SupportKPI label="Lending value"    value={data.lendingValue}    sub={data.lendingSub} tone="success" />
          <SupportKPI label="Min health factor" value={minHF.value} sub={minHF.sub} tone={minHFTone} last />
        </div>
      </section>

      {/* Wallet balances */}
      <WalletStrip balances={data.balances} />

      {/* Facilities with active accounts */}
      <FacilitiesWithAccounts rows={data.facilities} onOpenFacility={onOpenFacility} />

      {/* Lending positions */}
      <LendingPositions positions={data.lendingPositions} />
    </div>
  );
};

Object.assign(window, {
  Portfolio, HeroKPI, SupportKPI, WalletStrip, LendingPositionCard,
  FacilitiesWithAccounts, SectionHeader, SegmentControl,
});
