Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

65.8 KB
Raw Blame
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width,initial-scale=1" />
		<meta name="robots" content="noindex" />
		<meta name="referrer" content="strict-origin-when-cross-origin" />
		<title data-i18n="dashboard_portfolio.meta_title">Portfolio · Dashboard · three.ws</title>
		<link rel="icon" href="/favicon.ico" />
		<link rel="stylesheet" href="/fonts/fonts.css" />
		<link rel="stylesheet" href="/footer.css" />
		<style>
			:root {
				color-scheme: dark;
				--accent: #ffffff;
				--accent2: #ffffff;
				--ok: #2ed4a3;
				--warn: #ffb35c;
				--err: #ff6a6a;
				--border: #1d1d1d;
				--border-2: #242424;
				--bg: #000;
				--panel: #0c0c0c;
				--panel-2: #101010;
				--text: #f0f0f5;
				--muted: #6e6e82;
				--muted-2: #9a9ab0;
			}
			* { box-sizing: border-box; }
			html, body { background: var(--bg); }
			body {
				font: 14px/1.6 'Inter', -apple-system, system-ui, Segoe UI, Roboto, sans-serif;
				color: var(--text);
				margin: 0;
				min-height: 100vh;
				display: flex;
				flex-direction: column;
			}
			a { color: #888888; text-decoration: none; }

			/* ── Site header ───────────────────────────────────────────────── */
			.site-header {
				display: flex;
				align-items: center;
				gap: 12px;
				padding: 0 24px;
				border-bottom: 1px solid var(--border);
				position: sticky;
				top: 0;
				background: rgba(0, 0, 0, 0.88);
				backdrop-filter: blur(18px);
				-webkit-backdrop-filter: blur(18px);
				z-index: 20;
				height: 58px;
				flex-shrink: 0;
			}
			.site-header::after {
				content: '';
				position: absolute;
				left: 0; right: 0; bottom: -1px;
				height: 1px;
				background: linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.2) 35%, rgba(255,255,255,0.15) 60%, rgba(34,211,238,0.25) 80%, transparent 100%);
				pointer-events: none;
			}
			.site-brand {
				display: flex;
				align-items: center;
				gap: 8px;
				flex-shrink: 0;
				color: var(--text);
				font-weight: 600;
				font-size: 15px;
				letter-spacing: -0.01em;
			}
			.site-brand:hover { opacity: 0.85; }
			.wordmark-logo { height: 22px; width: auto; display: block; }

			.site-nav {
				display: flex;
				align-items: center;
				gap: 2px;
				margin-left: 6px;
				flex: 1;
				overflow-x: auto;
				scrollbar-width: none;
			}
			.site-nav::-webkit-scrollbar { display: none; }
			.site-nav a {
				padding: 6px 10px;
				border-radius: 6px;
				color: var(--muted);
				font-size: 13px;
				transition: color 0.14s, background 0.14s;
				white-space: nowrap;
			}
			.site-nav a:hover { color: var(--text); background: rgba(255,255,255,0.05); }
			.site-nav a.active { color: #fff; background: rgba(255,255,255,0.07); }

			.site-header-right {
				display: flex;
				align-items: center;
				gap: 8px;
				margin-left: auto;
				flex-shrink: 0;
			}

			/* ── Layout wrapper ────────────────────────────────────────────── */
			.page-wrap {
				display: flex;
				flex: 1;
				min-height: 0;
				align-items: flex-start;
			}

			/* ── Left sidebar ──────────────────────────────────────────────── */
			.dash-sidebar {
				width: 210px;
				flex-shrink: 0;
				border-right: 1px solid var(--border);
				position: sticky;
				top: 58px;
				height: calc(100vh - 58px);
				overflow-y: auto;
				padding: 18px 10px 40px;
				scrollbar-width: thin;
				scrollbar-color: var(--border-2) transparent;
				background: rgba(5,5,10,0.5);
			}
			.dash-sidebar::-webkit-scrollbar { width: 5px; }
			.dash-sidebar::-webkit-scrollbar-thumb { background: var(--border-2); border-radius: 99px; }

			.sidebar-section { margin-bottom: 22px; }
			.sidebar-label {
				font-size: 10.5px;
				font-weight: 600;
				letter-spacing: 0.08em;
				text-transform: uppercase;
				color: var(--muted);
				padding: 0 8px 6px;
			}
			.sidebar-link {
				display: flex;
				align-items: center;
				gap: 8px;
				padding: 7px 9px;
				border-radius: 7px;
				color: var(--muted-2);
				font-size: 13px;
				transition: color 0.13s, background 0.13s;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			.sidebar-link:hover { color: var(--text); background: rgba(255,255,255,0.04); }
			.sidebar-link.active {
				color: #fff;
				background: rgba(255,255,255,0.07);
				box-shadow: inset 2px 0 0 var(--accent);
			}
			.sidebar-link svg { flex-shrink: 0; opacity: 0.65; }
			.sidebar-link.active svg { opacity: 1; color: var(--ink-dim); }

			/* ── Main content ──────────────────────────────────────────────── */
			.dash-main {
				flex: 1;
				min-width: 0;
				padding: 28px 28px 64px;
				max-width: 1060px;
			}
			.page-title { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; margin: 0 0 4px; }
			.page-sub { color: var(--muted); font-size: 13.5px; margin: 0 0 24px; }

			/* ── Buttons ───────────────────────────────────────────────────── */
			.btn {
				padding: 8px 14px; border-radius: 8px; border: 0;
				font-size: 13px; font-weight: 600; cursor: pointer; font-family: inherit;
				background: rgba(255,255,255,0.06); color: var(--text);
				border: 1px solid var(--border-2);
				transition: all 0.13s ease;
				display: inline-flex; align-items: center; gap: 6px;
			}
			.btn:hover { background: rgba(255,255,255,0.1); border-color: rgba(255,255,255,0.18); }
			.btn:active { transform: scale(0.98); }
			.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
			.btn.primary:hover { background: rgba(255,255,255,0.9); border-color: rgba(255,255,255,0.9); }
			.btn.sec { background: #171717; color: #d0d0e0; border-color: var(--border); }
			.btn.sec:hover { background: #1f1f1f; }
			.btn.ghost { background: transparent; border-color: transparent; color: var(--muted-2); }
			.btn.ghost:hover { background: rgba(255,255,255,0.05); color: var(--text); }
			.btn.sm { padding: 5px 10px; font-size: 12px; border-radius: 6px; }
			.btn:disabled { opacity: 0.45; cursor: not-allowed; transform: none; }

			/* ── Hero card ─────────────────────────────────────────────────── */
			.hero {
				background:
					radial-gradient(900px 280px at 10% -30%, rgba(255,255,255,0.07), transparent 60%),
					radial-gradient(600px 200px at 90% -10%, rgba(255,92,168,0.1), transparent 60%),
					var(--panel);
				border: 1px solid var(--border-2);
				border-radius: 16px;
				padding: 24px 24px 0;
				margin-bottom: 16px;
				overflow: hidden;
				position: relative;
			}
			.hero-top {
				display: flex; align-items: flex-start; justify-content: space-between;
				gap: 16px; flex-wrap: wrap; margin-bottom: 18px;
			}
			.tot-label {
				font-size: 11px; font-weight: 600; letter-spacing: 0.1em;
				text-transform: uppercase; color: var(--muted);
			}
			.tot-value {
				font-size: 42px; font-weight: 700; letter-spacing: -0.03em;
				line-height: 1.05; margin-top: 6px; font-variant-numeric: tabular-nums;
				background: linear-gradient(135deg, #fff 0%, rgba(255,255,255,0.7) 100%);
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
				background-clip: text;
			}
			.tot-change {
				display: flex; align-items: center; gap: 10px; margin-top: 10px; font-size: 13px;
			}
			.chip {
				display: inline-flex; align-items: center; gap: 5px;
				padding: 4px 10px; border-radius: 99px; font-size: 12px; font-weight: 600;
				font-variant-numeric: tabular-nums; letter-spacing: 0.01em;
			}
			.chip.up { background: rgba(46,212,163,0.13); color: var(--ok); border: 1px solid rgba(46,212,163,0.2); }
			.chip.down { background: rgba(255,106,106,0.12); color: var(--err); border: 1px solid rgba(255,106,106,0.2); }
			.chip.flat { background: rgba(255,255,255,0.05); color: var(--muted-2); border: 1px solid var(--border-2); }
			.tot-meta { color: var(--muted); font-size: 13px; }
			.tot-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-start; padding-top: 4px; }

			/* ── Chart ─────────────────────────────────────────────────────── */
			.chart-wrap { position: relative; }
			#chart { height: 260px; margin: 0 -24px; }
			#chart-tooltip {
				position: absolute; top: 14px; left: 14px;
				background: rgba(6,6,12,0.88); border: 1px solid var(--border-2);
				border-radius: 8px; padding: 8px 12px;
				font-size: 12px; pointer-events: none; opacity: 0;
				transition: opacity 0.12s; min-width: 150px;
				backdrop-filter: blur(8px);
			}
			#chart-tooltip .tt-date { color: var(--muted); font-size: 11px; }
			#chart-tooltip .tt-val { font-size: 15px; font-weight: 600; margin-top: 2px; font-variant-numeric: tabular-nums; }
			#chart-empty {
				height: 260px; display: none; align-items: center; justify-content: center;
				color: var(--muted); font-size: 13px; flex-direction: column; gap: 8px;
				margin: 0 -24px;
			}
			.range-tabs {
				display: flex; gap: 3px; padding: 8px 0 14px;
				border-top: 1px solid var(--border); margin-top: 12px;
				justify-content: flex-end;
			}
			.range-tab {
				background: transparent; border: 0; cursor: pointer;
				color: var(--muted); font-size: 12px; font-weight: 600;
				padding: 5px 10px; border-radius: 6px; font-family: inherit;
				transition: all 0.12s;
			}
			.range-tab:hover { color: var(--muted-2); background: rgba(255,255,255,0.04); }
			.range-tab[aria-pressed="true"] {
				background: rgba(255,255,255,0.09); color: var(--ink);
				border: 0;
			}

			/* ── Stat cards ────────────────────────────────────────────────── */
			.stats-row {
				display: grid; grid-template-columns: repeat(4, 1fr);
				gap: 10px; margin: 0 0 18px;
			}
			.stat {
				background: var(--panel); border: 1px solid var(--border);
				border-radius: 12px; padding: 14px 16px;
				position: relative; overflow: hidden;
				transition: border-color 0.14s, box-shadow 0.14s;
			}
			.stat:hover { border-color: var(--border-2); box-shadow: 0 4px 18px -8px rgba(255,255,255,0.09); }
			.stat-icon {
				width: 28px; height: 28px; border-radius: 8px;
				display: grid; place-items: center;
				margin-bottom: 10px; font-size: 14px;
			}
			.stat-icon.purple { background: rgba(255,255,255,0.07); }
			.stat-icon.teal   { background: rgba(46,212,163,0.12); }
			.stat-icon.green  { background: rgba(46,212,163,0.12); }
			.stat-icon.red    { background: rgba(255,106,106,0.1); }
			.stat-label { color: var(--muted); font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600; }
			.stat-value { font-size: 20px; font-weight: 700; margin-top: 2px; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; }
			.stat-sub { color: var(--muted); font-size: 11.5px; margin-top: 3px; }

			/* ── Section headers ───────────────────────────────────────────── */
			.section-head {
				display: flex; align-items: center; justify-content: space-between;
				margin: 26px 0 12px;
			}
			.section-head h2 {
				font-size: 11.5px; margin: 0; color: var(--muted);
				text-transform: uppercase; letter-spacing: 0.08em; font-weight: 600;
				display: flex; align-items: center; gap: 7px;
			}
			.section-actions { display: flex; gap: 6px; align-items: center; }
			.count-badge {
				display: inline-flex; align-items: center; padding: 1px 7px;
				border-radius: 99px; background: rgba(255,255,255,0.05);
				border: 1px solid var(--border); color: var(--muted);
				font-size: 11px; font-weight: 600; font-variant-numeric: tabular-nums;
			}

			/* ── Holdings table ────────────────────────────────────────────── */
			.holdings {
				background: var(--panel); border: 1px solid var(--border);
				border-radius: 14px; overflow: hidden;
			}
			.h-head, .h-row {
				display: grid; grid-template-columns: 2.4fr 1fr 1fr 1.1fr 1fr;
				gap: 10px; align-items: center; padding: 11px 16px;
			}
			.h-head {
				font-size: 10.5px; color: var(--muted); text-transform: uppercase;
				letter-spacing: 0.08em; font-weight: 600;
				border-bottom: 1px solid var(--border);
				background: rgba(255,255,255,0.015);
			}
			.h-head button {
				background: none; border: 0; padding: 0; cursor: pointer;
				color: inherit; font: inherit; text-transform: inherit; letter-spacing: inherit;
				text-align: inherit; display: inline-flex; align-items: center; gap: 4px;
				transition: color 0.12s;
			}
			.h-head button:hover { color: var(--muted-2); }
			.h-row {
				border-bottom: 1px solid var(--border);
				cursor: pointer;
				transition: background 0.08s;
				text-decoration: none; color: inherit;
			}
			.h-row:last-child { border-bottom: 0; }
			.h-row:hover { background: rgba(255,255,255,0.026); }
			.tok-cell { display: flex; align-items: center; gap: 11px; min-width: 0; }
			.tok-logo {
				width: 32px; height: 32px; border-radius: 50%;
				background: var(--panel-2); flex-shrink: 0;
				display: inline-flex; align-items: center; justify-content: center;
				font-size: 10px; font-weight: 700; color: var(--muted-2);
				overflow: hidden; border: 1px solid var(--border);
			}
			.tok-logo img { width: 100%; height: 100%; object-fit: cover; }
			.tok-info { min-width: 0; }
			.tok-name {
				font-weight: 600; font-size: 13.5px; display: flex; align-items: center; gap: 6px;
				white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
			}
			.tok-sub { font-size: 11.5px; color: var(--muted); margin-top: 1px; }
			.cell-num { font-variant-numeric: tabular-nums; font-size: 13.5px; font-weight: 500; }
			.cell-num.muted { color: var(--muted); font-size: 12.5px; font-weight: 400; }
			.cell-right { text-align: right; }
			.alloc-bar { height: 3px; background: var(--border); border-radius: 99px; overflow: hidden; margin-top: 6px; }
			.alloc-bar > span { display: block; height: 100%; background: linear-gradient(90deg, var(--accent), var(--accent2)); border-radius: 99px; }
			.chain-pill {
				display: inline-flex; align-items: center; gap: 5px;
				font-size: 10px; padding: 2px 7px; border-radius: 99px;
				background: rgba(255,255,255,0.05); color: var(--muted-2);
				white-space: nowrap; text-transform: uppercase; letter-spacing: 0.06em; font-weight: 600;
				border: 1px solid var(--border);
			}
			.chain-pill.sol { background: rgba(20,241,149,0.1); color: var(--ok); border-color: rgba(20,241,149,0.15); }
			.chain-pill.evm { background: rgba(255,255,255,0.06); color: var(--ink-dim); border-color: rgba(255,255,255,0.10); }

			/* ── Wallet cards ──────────────────────────────────────────────── */
			.wallet-list { display: flex; flex-direction: column; gap: 10px; }
			.wcard {
				background: var(--panel); border: 1px solid var(--border);
				border-radius: 12px; padding: 16px 18px;
				transition: border-color 0.13s, box-shadow 0.13s;
			}
			.wcard:hover { border-color: var(--border-2); box-shadow: 0 4px 18px -8px rgba(0,0,0,0.35); }
			.wcard-head {
				display: flex; align-items: flex-start; justify-content: space-between;
				gap: 14px; flex-wrap: wrap;
			}
			.wcard-name {
				font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 8px;
			}
			.wcard-addr {
				font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
				font-size: 11.5px; color: var(--muted);
				display: inline-flex; align-items: center; gap: 6px; margin-top: 5px;
			}
			.copy-btn {
				background: none; border: none; color: var(--muted); cursor: pointer;
				padding: 2px 4px; font-size: 12px; border-radius: 4px;
				transition: color 0.12s, background 0.12s;
			}
			.copy-btn:hover { color: var(--muted-2); background: rgba(255,255,255,0.06); }
			.wcard-usd {
				font-size: 17px; font-weight: 700; font-variant-numeric: tabular-nums;
				text-align: right; letter-spacing: -0.015em;
			}
			.wcard-actions {
				display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; margin-top: 8px;
			}

			/* ── Empty & error states ──────────────────────────────────────── */
			.empty {
				text-align: center; padding: 44px 20px;
				border: 1px dashed var(--border-2); border-radius: 12px;
				color: var(--muted);
			}
			.empty p { margin: 0 0 6px; font-size: 13.5px; }
			.empty p:first-child { font-weight: 600; font-size: 15px; color: var(--muted-2); }
			.empty .btn { margin-top: 14px; }
			.err-banner {
				padding: 12px 14px; background: rgba(255,80,80,0.08);
				border: 1px solid rgba(255,80,80,0.22); border-radius: 10px;
				color: #ffb0b0; margin-bottom: 14px; display: none; font-size: 13px;
			}

			/* ── Skeleton loader ───────────────────────────────────────────── */
			.skeleton {
				background: linear-gradient(90deg, var(--panel) 0%, var(--panel-2) 50%, var(--panel) 100%);
				background-size: 200% 100%;
				animation: shimmer 1.5s ease-in-out infinite;
				border-radius: 10px;
			}
			@keyframes shimmer {
				from { background-position: 200% 0; }
				to   { background-position: -200% 0; }
			}

			/* ── Modal / scrim ─────────────────────────────────────────────── */
			.scrim {
				position: fixed; inset: 0; background: rgba(0,0,0,0.75);
				display: none; align-items: center; justify-content: center;
				z-index: 100; padding: 20px;
				backdrop-filter: blur(6px);
				-webkit-backdrop-filter: blur(6px);
			}
			.scrim[data-open="true"] { display: flex; }
			.modal {
				background: #0e0e0e; border: 1px solid var(--border-2);
				border-radius: 14px; padding: 24px;
				width: 100%; max-width: 460px; max-height: 90vh; overflow-y: auto;
				box-shadow: 0 20px 60px rgba(0,0,0,0.6);
			}
			.modal h3 { margin: 0 0 4px; font-size: 17px; letter-spacing: -0.01em; }
			.modal .sub { color: var(--muted); font-size: 13px; margin: 0 0 18px; }
			.modal label { display: block; margin-bottom: 12px; }
			.modal label span { display: block; font-size: 12px; color: var(--muted); margin-bottom: 5px; font-weight: 500; }
			.modal input, .modal select {
				width: 100%; padding: 10px 12px; border-radius: 8px;
				border: 1px solid var(--border-2); background: #090909; color: #eee;
				font-size: 14px; font-family: inherit;
				transition: border-color 0.13s, box-shadow 0.13s;
			}
			.modal input:focus, .modal select:focus {
				outline: none; border-color: rgba(255,255,255,0.28);
				box-shadow: 0 0 0 3px rgba(255,255,255,0.06);
			}
			.modal input[data-mono] { font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: 13px; }
			.modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 20px; }
			.qr-wrap { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 14px 0; }
			.qr-wrap canvas { background: #fff; padding: 10px; border-radius: 10px; }
			.qr-addr {
				font-family: 'JetBrains Mono', ui-monospace, monospace;
				font-size: 11.5px; color: #ccc; word-break: break-all;
				text-align: center; max-width: 100%;
			}

			/* ── Responsive ────────────────────────────────────────────────── */
			@media (max-width: 1024px) {
				.dash-sidebar { width: 180px; }
			}
			@media (max-width: 820px) {
				.dash-sidebar { display: none; }
				.dash-main { padding: 18px 16px 60px; }
				.h-head, .h-row { grid-template-columns: 2fr 1.2fr 1.2fr; }
				.h-head .col-amount, .h-row .col-amount,
				.h-head .col-alloc, .h-row .col-alloc { display: none; }
				.stats-row { grid-template-columns: repeat(2, 1fr); }
				.tot-value { font-size: 34px; }
				.site-nav { display: none; }
			}
			@media (max-width: 500px) {
				.stats-row { grid-template-columns: 1fr 1fr; }
				.stat-value { font-size: 17px; }
			}

			body[data-auth-pending] { visibility: hidden; }
		</style>
	</head>
	<body data-auth-pending>

		<!-- Site header -->
		<header class="site-header">
			<a href="/" class="site-brand">
				<img src="/three.svg" alt="three.ws" class="wordmark-logo" />
			</a>
			<nav class="site-nav" aria-label="Primary">
				<a href="/app" data-i18n="dashboard_portfolio.viewer">Viewer</a>
				<a href="/create" data-i18n="dashboard_portfolio.create">Create</a>
				<a href="/discover" data-i18n="dashboard_portfolio.discover">Discover</a>
				<a href="/widgets" data-i18n="dashboard_portfolio.widgets">Widgets</a>
				<a href="/studio" data-i18n="dashboard_portfolio.studio">Studio</a>
				<a href="/docs" data-i18n="dashboard_portfolio.docs">Docs</a>
				<a href="/my-agents" data-i18n="dashboard_portfolio.my_agents">My Agents</a>
				<a href="/dashboard" class="active" aria-current="page" data-i18n="dashboard_portfolio.dashboard">Dashboard</a>
			</nav>
			<div class="site-header-right" id="header-user-slot"></div>
		</header>

		<div class="page-wrap">
			<!-- Left sidebar -->
			<aside class="dash-sidebar" aria-label="Dashboard navigation">
				<div class="sidebar-section">
					<div class="sidebar-label">Finances</div>
					<a href="/dashboard/portfolio" class="sidebar-link active" aria-current="page">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
						Portfolio
					</a>
					<a href="/dashboard/tokens" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M15 9.354a4 4 0 1 0 0 5.292"/></svg>
						Tokens
					</a>
					<a href="/dashboard/wallets" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4Z"/></svg>
						Wallets
					</a>
					<a href="/dashboard-classic/payments" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/></svg>
						Payments
					</a>
					<a href="/dashboard-classic/revenue" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" x2="12" y1="2" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
						Revenue
					</a>
					<a href="/dashboard-classic/earnings" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20V10"/><path d="M18 20V4"/><path d="M6 20v-6"/></svg>
						Earnings
					</a>
					<a href="/dashboard-classic/withdrawals" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
						Withdrawals
					</a>
				</div>
				<div class="sidebar-section">
					<div class="sidebar-label">Agents</div>
					<a href="/dashboard/agents" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="5"/><path d="M20 21a8 8 0 1 0-16 0"/></svg>
						Agents
					</a>
					<a href="/dashboard/avatars" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a5 5 0 1 0 5 5"/><path d="M20 21a8 8 0 1 0-16 0"/></svg>
						Avatars
					</a>
					<a href="/dashboard/widgets" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="7" height="7" x="3" y="3" rx="1"/><rect width="7" height="7" x="14" y="3" rx="1"/><rect width="7" height="7" x="14" y="14" rx="1"/><rect width="7" height="7" x="3" y="14" rx="1"/></svg>
						Widgets
					</a>
					<a href="/my-agents" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>
						On-chain (ERC-8004)
					</a>
				</div>
				<div class="sidebar-section">
					<div class="sidebar-label">Tools</div>
					<a href="/dashboard/strategy" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 20h.01"/><path d="M7 20v-4"/><path d="M12 20v-8"/><path d="M17 20V8"/><path d="M22 4v16"/></svg>
						Strategy
					</a>
					<a href="/dashboard/memory" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5"/><path d="M3 12c0 1.66 4.03 3 9 3s9-1.34 9-3"/></svg>
						Memory
					</a>
					<a href="/dashboard-classic/keys" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/></svg>
						API keys
					</a>
					<a href="/dashboard/sns" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" x2="22" y1="12" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
						SNS domains
					</a>
					<a href="/dashboard/actions" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3L14.5 4z"/><circle cx="12" cy="13" r="3"/></svg>
						Action log
					</a>
					<a href="/dashboard/sessions" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
						Sessions
					</a>
					<a href="/dashboard/account" class="sidebar-link">
						<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"/></svg>
						Account
					</a>
				</div>
			</aside>

			<!-- Main content -->
			<main class="dash-main" id="main">
				<h1 class="page-title" data-i18n="dashboard_portfolio.portfolio">Portfolio</h1>
				<p class="page-sub" data-i18n="dashboard_portfolio.real_time_value_across_every_agent_wallet">Real-time value across every agent wallet under your account.</p>

				<div id="error" class="err-banner" role="alert"></div>

				<!-- Hero chart card -->
				<div class="hero">
					<div class="hero-top">
						<div>
							<div class="tot-label">Total value</div>
							<div class="tot-value" id="tot-value">—</div>
							<div class="tot-change">
								<span class="chip flat" id="tot-change-chip">—</span>
								<span class="tot-meta" id="tot-meta" data-i18n="dashboard_portfolio.loading_live_balances">Loading live balances…</span>
							</div>
						</div>
						<div class="tot-actions">
							<button id="refresh-btn" class="btn primary">
								<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>
								Refresh
							</button>
						</div>
					</div>
					<div class="chart-wrap">
						<div id="chart"></div>
						<div id="chart-empty">
							<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.25"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
							Hit Refresh to capture your first snapshot.
						</div>
						<div id="chart-tooltip">
							<div class="tt-date"></div>
							<div class="tt-val"></div>
						</div>
					</div>
					<div class="range-tabs" id="range-tabs" role="group" aria-label="Time range">
						<button class="range-tab" data-days="1" data-i18n="dashboard_portfolio.1d">1D</button>
						<button class="range-tab" data-days="7" data-i18n="dashboard_portfolio.7d">7D</button>
						<button class="range-tab" data-days="30" aria-pressed="true" data-i18n="dashboard_portfolio.30d">30D</button>
						<button class="range-tab" data-days="90" data-i18n="dashboard_portfolio.90d">90D</button>
						<button class="range-tab" data-days="365" data-i18n="dashboard_portfolio.1y">1Y</button>
						<button class="range-tab" data-days="0" data-i18n="dashboard_portfolio.all">All</button>
					</div>
				</div>

				<!-- Stat cards -->
				<div class="stats-row">
					<div class="stat">
						<div class="stat-icon purple">
							<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#888888" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M15 9.354a4 4 0 1 0 0 5.292"/></svg>
						</div>
						<div class="stat-label">Assets</div>
						<div class="stat-value" id="stat-assets">—</div>
						<div class="stat-sub" id="stat-assets-sub">across all wallets</div>
					</div>
					<div class="stat">
						<div class="stat-icon teal">
							<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#2ed4a3" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4Z"/></svg>
						</div>
						<div class="stat-label">Wallets</div>
						<div class="stat-value" id="stat-wallets">—</div>
						<div class="stat-sub" id="stat-wallets-sub">solana + evm</div>
					</div>
					<div class="stat">
						<div class="stat-icon green">
							<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#2ed4a3" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 7 13.5 15.5 8.5 10.5 2 17"/><path d="M16 7h6v6"/></svg>
						</div>
						<div class="stat-label">Best 24h</div>
						<div class="stat-value" id="stat-best">—</div>
						<div class="stat-sub" id="stat-best-sub"></div>
					</div>
					<div class="stat">
						<div class="stat-icon red">
							<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#ff6a6a" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 17 13.5 8.5 8.5 13.5 2 7"/><path d="M16 17h6v-6"/></svg>
						</div>
						<div class="stat-label">Worst 24h</div>
						<div class="stat-value" id="stat-worst">—</div>
						<div class="stat-sub" id="stat-worst-sub"></div>
					</div>
				</div>

				<!-- Holdings -->
				<div class="section-head">
					<h2>
						<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
						All holdings
					</h2>
					<div class="section-actions">
						<span class="count-badge" id="holding-count" style="display:none"></span>
					</div>
				</div>
				<div id="holdings" class="holdings">
					<div style="padding:22px 16px">
						<div class="skeleton" style="height:38px;margin-bottom:10px"></div>
						<div class="skeleton" style="height:38px;margin-bottom:10px"></div>
						<div class="skeleton" style="height:38px"></div>
					</div>
				</div>

				<!-- Wallets -->
				<div class="section-head">
					<h2>
						<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4Z"/></svg>
						Wallets
					</h2>
					<span class="count-badge" id="wallet-count" style="display:none"></span>
				</div>
				<div id="wallets" class="wallet-list">
					<div style="padding:22px 0">
						<div class="skeleton" style="height:80px;margin-bottom:10px;border-radius:12px"></div>
						<div class="skeleton" style="height:80px;border-radius:12px"></div>
					</div>
				</div>
			</main>
		</div>

		<!-- Send / Receive modal -->
		<div id="scrim" class="scrim" role="dialog" aria-modal="true" aria-label="Wallet action">
			<div class="modal" id="modal-body"></div>
		</div>

		<!-- Footer -->
		<footer class="h-footer-horizon">
			<div class="h-footer-glow-line" aria-hidden="true"></div>
			<div class="h-footer-floor" aria-hidden="true"></div>
			<div class="h-footer-haze" aria-hidden="true"></div>
			<div class="h-footer-watermark" aria-hidden="true">three.ws</div>
			<div class="h-footer-inner">
				<div class="h-footer-brand-col">
					<div class="h-footer-brand">
						<img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" />
						<span data-i18n="dashboard_portfolio.three_ws">three.ws</span>
					</div>
					<p class="h-footer-tagline" data-i18n="dashboard_portfolio.give_your_ai_a_body">Give your AI a body.</p>
				</div>
				<nav class="h-footer-links" aria-label="Footer">
					<a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener noreferrer" data-i18n="dashboard_portfolio.github">GitHub</a>
					<a href="/create" data-i18n="dashboard_portfolio.create_2">Create</a>
					<a href="/studio" data-i18n="dashboard_portfolio.studio_2">Studio</a>
					<a href="/widgets" data-i18n="dashboard_portfolio.widgets_2">Widgets</a>
					<a href="/discover" data-i18n="dashboard_portfolio.discover_2">Discover</a>
					<a href="/docs" data-i18n="dashboard_portfolio.docs_2">Docs</a>
					<a href="/legal/privacy" data-i18n="dashboard_portfolio.privacy">Privacy</a>
					<a href="/legal/tos" data-i18n="dashboard_portfolio.terms">Terms</a>
				</nav>
			</div>
			<div class="h-footer-bottom">
				<p class="h-footer-legal" data-i18n="dashboard_portfolio.2026_three_ws_all_rights_reserved">© 2026 three.ws — All rights reserved.</p>
				<div class="h-footer-badges">
					<span class="h-footer-badge" aria-label="System status" data-i18n-html="dashboard_portfolio.all_systems_normal" data-i18n-attr="aria-label:dashboard_portfolio.system_status_arialabel">
						<span class="h-footer-status-dot" aria-hidden="true"></span>
						<span>All systems normal</span>
					</span>
					<span class="h-footer-badge">
						<svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm0 14.5A6.5 6.5 0 1 1 8 1.5a6.5 6.5 0 0 1 0 13zm-1-9.25a1 1 0 1 1 2 0v3.5a1 1 0 1 1-2 0v-3.5zm1 6.5a1.1 1.1 0 1 1 0-2.2 1.1 1.1 0 0 1 0 2.2z"/></svg>
						Transparent by default
					</span>
					<a class="h-footer-badge" href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener noreferrer" aria-label="View source on GitHub" data-i18n-attr="aria-label:dashboard_portfolio.view_source_on_github_arialabel">
						<svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
						Open source
					</a>
				</div>
			</div>
		</footer>

		<script type="module">
			import { renderHeaderUser } from '/src/header-user.js';

			const apiUrl = '/api';
			let csrfToken = null;
			let chart = null;
			let series = null;
			let chartEl = null;
			let chartTooltip = null;
			let currentSummary = null;
			let currentHistory = [];
			let activeDays = 30;
			let sortBy = 'usd';
			let sortDir = 'desc';

			const $ = (id) => document.getElementById(id);

			function fmtUsd(n, opts = {}) {
				if (!Number.isFinite(n)) return '$0.00';
				const abs = Math.abs(n);
				if (abs >= 1_000_000) return '$' + (n / 1_000_000).toFixed(2) + 'M';
				if (abs >= 10_000) return '$' + n.toLocaleString('en-US', { maximumFractionDigits: 0 });
				if (abs >= 1) return '$' + n.toLocaleString('en-US', { maximumFractionDigits: 2 });
				if (abs > 0) {
					if (opts.precise) return '$' + n.toLocaleString('en-US', { maximumFractionDigits: 6 });
					return '$' + n.toFixed(abs < 0.01 ? 4 : 2);
				}
				return '$0.00';
			}
			function fmtPct(n) {
				if (!Number.isFinite(n)) return '—';
				const sign = n >= 0 ? '+' : '';
				return sign + n.toFixed(2) + '%';
			}
			function fmtAmt(n) {
				if (!Number.isFinite(n) || n === 0) return '0';
				if (n < 0.0001) return n.toExponential(2);
				if (n < 1) return n.toFixed(4);
				if (n < 1000) return n.toFixed(3);
				return n.toLocaleString('en-US', { maximumFractionDigits: 2 });
			}
			function shortAddr(a) {
				if (!a) return '';
				return a.length > 14 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;
			}
			function escapeHtml(s) {
				return String(s ?? '').replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
			}
			function chainLabel(chain, chain_id) {
				if (chain === 'solana') return 'Solana';
				if (chain_id === 8453) return 'Base';
				return 'Ethereum';
			}
			function setError(msg) {
				const el = $('error');
				if (!msg) { el.style.display = 'none'; return; }
				el.textContent = msg;
				el.style.display = 'block';
			}

			// ── Auth ──────────────────────────────────────────────────────────

			async function fetchUser() {
				const res = await fetch(`${apiUrl}/auth/me`, { credentials: 'include' });
				const data = res.ok ? await res.json() : null;
				if (!data?.user) {
					location.href = '/login?next=' + encodeURIComponent(location.pathname);
					return null;
				}
				document.body.removeAttribute('data-auth-pending');
				return data;
			}

			async function getCsrf() {
				if (csrfToken) return csrfToken;
				const r = await fetch(`${apiUrl}/csrf-token`, { credentials: 'include' });
				if (!r.ok) throw new Error('CSRF token fetch failed');
				const d = await r.json();
				csrfToken = d?.data?.token;
				return csrfToken;
			}

			// ── Data loading ──────────────────────────────────────────────────

			async function loadHistory(days) {
				const q = days && days > 0 ? `?days=${days}` : '?days=365';
				const r = await fetch(`${apiUrl}/portfolio/history${q}`, { credentials: 'include' });
				if (!r.ok) return [];
				const d = await r.json();
				return d.points || [];
			}

			async function loadSummary({ snapshot = false } = {}) {
				const url = `${apiUrl}/portfolio/summary${snapshot ? '?snapshot=1' : ''}`;
				const r = await fetch(url, { credentials: 'include' });
				if (!r.ok) {
					const e = await r.json().catch(() => ({}));
					throw new Error(e.error_description || 'Failed to load portfolio');
				}
				return r.json();
			}

			// ── Holdings aggregation ──────────────────────────────────────────

			function aggregateHoldings(summary) {
				const map = new Map();
				for (const w of summary.wallets) {
					if (!w.ok) continue;
					const native = w.native;
					if (native && (native.amount > 0 || native.usd > 0)) {
						const key = `${w.chain}:native`;
						let entry = map.get(key);
						if (!entry) {
							entry = { key, chain: w.chain, chain_id: w.chain_id ?? null, id: 'native', is_native: true, symbol: native.symbol, name: native.name || native.symbol, logo: null, price: native.price || 0, change24h: native.change24h ?? null, amount: 0, usd: 0, wallets: [] };
							map.set(key, entry);
						}
						entry.amount += Number(native.amount || 0);
						entry.usd += Number(native.usd || 0);
						entry.wallets.push({ agent_id: w.agent_id, agent_name: w.agent_name, address: w.address, amount: Number(native.amount || 0), usd: Number(native.usd || 0) });
					}
					for (const t of (w.tokens || [])) {
						const id = t.mint || t.contract;
						if (!id) continue;
						const key = `${w.chain}:${id.toLowerCase()}`;
						let entry = map.get(key);
						if (!entry) {
							entry = { key, chain: w.chain, chain_id: w.chain_id ?? null, id, is_native: false, symbol: t.symbol || id.slice(0, 6), name: t.name || t.symbol || id.slice(0, 8), logo: t.logo || null, price: t.price || 0, change24h: t.change24h ?? null, amount: 0, usd: 0, wallets: [] };
							map.set(key, entry);
						}
						entry.amount += Number(t.amount || 0);
						entry.usd += Number(t.usd || 0);
						entry.wallets.push({ agent_id: w.agent_id, agent_name: w.agent_name, address: w.address, amount: Number(t.amount || 0), usd: Number(t.usd || 0) });
					}
				}
				return Array.from(map.values());
			}

			function sortHoldings(rows) {
				const dir = sortDir === 'asc' ? 1 : -1;
				const cmp = {
					usd: (a, b) => (a.usd - b.usd) * dir,
					amount: (a, b) => (a.amount - b.amount) * dir,
					change: (a, b) => ((a.change24h ?? -Infinity) - (b.change24h ?? -Infinity)) * dir,
					symbol: (a, b) => a.symbol.localeCompare(b.symbol) * dir,
				}[sortBy] || ((a, b) => (a.usd - b.usd) * dir);
				return [...rows].sort(cmp);
			}

			// ── Render ────────────────────────────────────────────────────────

			function renderTotal(summary) {
				$('tot-value').textContent = fmtUsd(summary.total_usd);
				const at = new Date(summary.captured_at);
				$('tot-meta').textContent = `Updated ${at.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
			}

			function renderHistoryChange(points, totalNow) {
				const chip = $('tot-change-chip');
				if (!points.length) { chip.className = 'chip flat'; chip.textContent = '—'; return; }
				const first = points[0].usd;
				const delta = totalNow - first;
				const pct = first > 0 ? (delta / first) * 100 : 0;
				const cls = delta > 0 ? 'up' : delta < 0 ? 'down' : 'flat';
				chip.className = 'chip ' + cls;
				const sign = delta > 0 ? '+' : delta < 0 ? '−' : '';
				chip.innerHTML = `${sign}${fmtUsd(Math.abs(delta))} <span style="opacity:0.7">${fmtPct(pct)}</span>`;
			}

			function renderStats(summary, holdings) {
				const countEl = $('stat-assets');
				const walletEl = $('stat-wallets');
				countEl.textContent = holdings.length;
				walletEl.textContent = summary.wallets.length;
				const sol = summary.wallets.filter((w) => w.chain === 'solana').length;
				const evm = summary.wallets.filter((w) => w.chain === 'evm').length;
				$('stat-wallets-sub').textContent = `${sol} solana · ${evm} evm`;
				$('stat-assets-sub').textContent = 'across all wallets';

				const withChange = holdings.filter((h) => Number.isFinite(h.change24h) && h.usd > 0.5);
				if (withChange.length) {
					const sorted = [...withChange].sort((a, b) => b.change24h - a.change24h);
					const best = sorted[0];
					const worst = sorted[sorted.length - 1];
					$('stat-best').textContent = fmtPct(best.change24h);
					$('stat-best').style.color = best.change24h >= 0 ? 'var(--ok)' : 'var(--err)';
					$('stat-best-sub').textContent = best.symbol;
					$('stat-worst').textContent = fmtPct(worst.change24h);
					$('stat-worst').style.color = worst.change24h >= 0 ? 'var(--ok)' : 'var(--err)';
					$('stat-worst-sub').textContent = worst.symbol;
				} else {
					['stat-best','stat-worst'].forEach((id) => { $(id).textContent = '—'; $(id).style.color = ''; });
					$('stat-best-sub').textContent = '';
					$('stat-worst-sub').textContent = '';
				}
			}

			function renderHoldings(summary) {
				const rows = aggregateHoldings(summary);
				const totalUsd = summary.total_usd || rows.reduce((s, r) => s + (r.usd || 0), 0);
				renderStats(summary, rows);
				const sorted = sortHoldings(rows);

				const cntEl = $('holding-count');
				if (rows.length) { cntEl.textContent = `${rows.length} assets`; cntEl.style.display = ''; }
				else { cntEl.style.display = 'none'; }

				const container = $('holdings');
				if (!rows.length) {
					container.innerHTML = `
						<div class="empty">
							<p>No holdings yet.</p>
							<p style="color:var(--muted)">Fund any agent wallet to see live balances here.</p>
							<a href="/dashboard/agents" class="btn sec sm">Manage agents</a>
						</div>`;
					return;
				}
				const arrow = (key) => sortBy === key ? (sortDir === 'asc' ? ' ↑' : ' ↓') : '';
				const head = `
					<div class="h-head">
						<div><button data-sort="symbol">Asset${arrow('symbol')}</button></div>
						<div class="cell-right"><button data-sort="usd">Value${arrow('usd')}</button></div>
						<div class="cell-right col-amount"><button data-sort="amount">Holdings${arrow('amount')}</button></div>
						<div class="cell-right"><button data-sort="change">24h${arrow('change')}</button></div>
						<div class="cell-right col-alloc">Alloc.</div>
					</div>`;
				const body = sorted.map((r) => {
					const alloc = totalUsd > 0 ? (r.usd / totalUsd) * 100 : 0;
					const changeColor = r.change24h == null ? 'var(--muted)' : (r.change24h >= 0 ? 'var(--ok)' : 'var(--err)');
					const logoInner = r.logo
						? `<img src="${escapeHtml(r.logo)}" alt="" loading="lazy" data-fallback="parent-text" data-fallback-text="${escapeHtml((r.symbol || '?').slice(0,3))}" />`
						: escapeHtml((r.symbol || '?').slice(0, 3));
					const chainCls = r.chain === 'solana' ? 'sol' : 'evm';
					const chainText = r.chain === 'solana' ? 'SOL' : 'EVM';
					const chainIdQs = r.chain_id ? `&chain_id=${encodeURIComponent(r.chain_id)}` : '';
					const href = `/dashboard/portfolio/asset?chain=${encodeURIComponent(r.chain)}&id=${encodeURIComponent(r.is_native ? 'native' : r.id)}${chainIdQs}`;
					return `
						<a class="h-row" href="${escapeHtml(href)}">
							<div class="tok-cell">
								<span class="tok-logo">${logoInner}</span>
								<div class="tok-info">
									<div class="tok-name">${escapeHtml(r.symbol)} <span class="chain-pill ${chainCls}">${chainText}</span></div>
									<div class="tok-sub">${escapeHtml(r.name || r.symbol)}${r.price ? ' · ' + fmtUsd(r.price, { precise: true }) : ''}</div>
								</div>
							</div>
							<div class="cell-num cell-right">${fmtUsd(r.usd)}</div>
							<div class="cell-num cell-right muted col-amount">${fmtAmt(r.amount)} ${escapeHtml(r.symbol)}</div>
							<div class="cell-num cell-right" style="color:${changeColor}">${r.change24h == null ? '—' : fmtPct(r.change24h)}</div>
							<div class="cell-right col-alloc">
								<div style="font-size:12.5px;font-weight:500">${alloc.toFixed(1)}%</div>
								<div class="alloc-bar"><span style="width:${Math.min(100, alloc).toFixed(2)}%"></span></div>
							</div>
						</a>`;
				}).join('');
				container.innerHTML = head + body;
				container.querySelectorAll('[data-sort]').forEach((btn) => {
					btn.addEventListener('click', (e) => {
						e.preventDefault();
						const key = btn.dataset.sort;
						if (sortBy === key) sortDir = sortDir === 'asc' ? 'desc' : 'asc';
						else { sortBy = key; sortDir = key === 'symbol' ? 'asc' : 'desc'; }
						renderHoldings(currentSummary);
					});
				});
			}

			function renderWallets(summary) {
				const container = $('wallets');
				const cntEl = $('wallet-count');
				if (summary.wallets.length) { cntEl.textContent = `${summary.wallets.length}`; cntEl.style.display = ''; }
				else { cntEl.style.display = 'none'; }

				if (!summary.wallets.length) {
					container.innerHTML = `
						<div class="empty">
							<p>No agent wallets yet.</p>
							<p style="color:var(--muted)">Create an agent and you'll get a Solana + EVM custodial wallet automatically.</p>
							<a href="/dashboard/agents" class="btn sec sm">Manage agents</a>
						</div>`;
					return;
				}
				container.innerHTML = summary.wallets.map(walletCard).join('');
				for (const w of summary.wallets) {
					const id = `w-${w.chain}-${w.address}`.replace(/[^a-z0-9-]/gi, '_');
					document.querySelectorAll(`[data-wid="${id}"]`).forEach((b) => {
						b.addEventListener('click', () => onAction(b.dataset.kind, w));
					});
				}
				container.querySelectorAll('.copy-btn').forEach((b) =>
					b.addEventListener('click', () => {
						navigator.clipboard.writeText(b.dataset.copy);
						const orig = b.textContent;
						b.textContent = '✓';
						setTimeout(() => (b.textContent = orig), 1200);
					}),
				);
			}

			function walletCard(w) {
				const id = `w-${w.chain}-${w.address}`.replace(/[^a-z0-9-]/gi, '_');
				const chainCls = w.ok === false ? '' : (w.chain === 'solana' ? 'sol' : 'evm');
				const chainText = w.ok === false
					? `<span class="chain-pill" style="background:rgba(255,80,80,0.12);color:var(--err);border-color:rgba(255,80,80,0.2)" title="${escapeHtml(w.error || '')}">${escapeHtml(w.chain)} · error</span>`
					: `<span class="chain-pill ${chainCls}">${chainLabel(w.chain, w.chain_id)}</span>`;
				const tokenCount = (w.tokens || []).length + (w.native?.amount > 0 ? 1 : 0);
				const snsLine = w.sns
					? `<span style="color:#a08cff;font-family:inherit">${escapeHtml(w.sns)}</span><span style="color:var(--border-2);margin:0 2px">·</span>`
					: '';
				return `
					<div class="wcard">
						<div class="wcard-head">
							<div style="min-width:0">
								<div class="wcard-name">${escapeHtml(w.agent_name)} ${chainText}</div>
								<div class="wcard-addr">
									${snsLine}
									<span>${shortAddr(w.address)}</span>
									<button class="copy-btn" data-copy="${escapeHtml(w.address)}" title="Copy address" aria-label="Copy wallet address">📋</button>
									<span style="color:var(--border-2);margin:0 2px">·</span>
									<span>${tokenCount} ${tokenCount === 1 ? 'asset' : 'assets'}</span>
								</div>
							</div>
							<div>
								<div class="wcard-usd">${fmtUsd(w.usd || 0)}</div>
								<div class="wcard-actions">
									<button class="btn ghost sm" data-wid="${id}" data-kind="receive">Receive</button>
									<button class="btn sec sm" data-wid="${id}" data-kind="send">Send</button>
								</div>
							</div>
						</div>
					</div>`;
			}

			// ── Third-party modules ───────────────────────────────────────────

			// Every CDN module on this page goes through /load-module.js, which
			// races the same package version across esm.sh, jsdelivr and unpkg and
			// rejects with a typed error naming every host it tried. A bare
			// import('https://esm.sh/...') made one CDN outage, one corporate
			// proxy or one ad blocker enough to blank the feature with no message.
			async function loadCdnModule(url) {
				const { loadModule } = await import('/load-module.js');
				return loadModule(url);
			}

			// ── Chart ─────────────────────────────────────────────────────────

			async function ensureChart() {
				if (chart) return;
				const mod = await loadCdnModule('https://esm.sh/[email protected]');
				const { createChart, AreaSeries } = mod;
				chartEl = $('chart');
				chartTooltip = $('chart-tooltip');
				chart = createChart(chartEl, {
					layout: { background: { color: 'transparent' }, textColor: '#555', fontFamily: 'inherit', fontSize: 11 },
					grid: { vertLines: { visible: false }, horzLines: { color: '#0f0f0f' } },
					rightPriceScale: { borderVisible: false, scaleMargins: { top: 0.15, bottom: 0.05 } },
					timeScale: { borderVisible: false, timeVisible: false, secondsVisible: false },
					crosshair: {
						vertLine: { color: '#2c2c2c', style: 0, width: 1, labelVisible: false },
						horzLine: { color: '#2c2c2c', style: 0, width: 1, labelVisible: true },
					},
					handleScroll: false,
					handleScale: false,
				});
				const seriesOpts = {
					lineColor: '#888888',
					topColor: 'rgba(255,255,255,0.16)',
					bottomColor: 'rgba(255,255,255,0)',
					lineWidth: 2,
					priceFormat: { type: 'price', precision: 2, minMove: 0.01 },
					crosshairMarkerRadius: 5,
					crosshairMarkerBorderColor: '#888888',
					crosshairMarkerBackgroundColor: '#fff',
				};
				series = chart.addAreaSeries
					? chart.addAreaSeries(seriesOpts)
					: chart.addSeries(AreaSeries, seriesOpts);

				chart.subscribeCrosshairMove((param) => {
					if (!param.time || !param.seriesData?.size) { chartTooltip.style.opacity = '0'; return; }
					const pt = param.seriesData.get(series);
					if (!pt) { chartTooltip.style.opacity = '0'; return; }
					const date = new Date(param.time * 1000);
					chartTooltip.querySelector('.tt-date').textContent = date.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' });
					chartTooltip.querySelector('.tt-val').textContent = fmtUsd(pt.value);
					chartTooltip.style.opacity = '1';
				});

				new ResizeObserver(() => {
					if (chartEl.clientWidth) chart.applyOptions({ width: chartEl.clientWidth, height: chartEl.clientHeight });
				}).observe(chartEl);
			}

			function filterPointsByDays(points, days) {
				if (!days || days <= 0) return points;
				const cutoff = Date.now() - days * 86400_000;
				return points.filter((p) => new Date(p.t).getTime() >= cutoff);
			}

			async function renderChart(points, totalNow) {
				const filtered = filterPointsByDays(points, activeDays);
				renderHistoryChange(filtered, totalNow);
				if (!filtered || filtered.length < 1) {
					$('chart').style.display = 'none';
					$('chart-empty').style.display = 'flex';
					return;
				}
				$('chart').style.display = 'block';
				$('chart-empty').style.display = 'none';
				try {
					await ensureChart();
				} catch (err) {
					// The charting library is unreachable. The balances above are
					// real and already rendered, so say what is missing and why
					// rather than leaving an empty 260px hole.
					$('chart').style.display = 'none';
					const empty = $('chart-empty');
					empty.style.display = 'flex';
					empty.textContent = err?.message || 'The chart library could not be loaded.';
					return;
				}
				const data = filtered
					.map((p) => ({ time: Math.floor(new Date(p.t).getTime() / 1000), value: Number(p.usd) }))
					.filter((d) => Number.isFinite(d.time) && Number.isFinite(d.value))
					.sort((a, b) => a.time - b.time)
					.filter((d, i, arr) => i === 0 || d.time !== arr[i - 1].time);
				if (!data.length) {
					$('chart').style.display = 'none';
					$('chart-empty').style.display = 'flex';
					return;
				}
				series.setData(data);
				chart.timeScale().fitContent();
			}

			// ── Modal actions ─────────────────────────────────────────────────

			function openModal(html, after) {
				$('modal-body').innerHTML = html;
				$('scrim').setAttribute('data-open', 'true');
				if (after) after();
			}
			function closeModal() { $('scrim').removeAttribute('data-open'); }
			$('scrim').addEventListener('click', (e) => { if (e.target.id === 'scrim') closeModal(); });
			document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeModal(); });

			async function onAction(kind, w) {
				if (kind === 'receive') return openReceive(w);
				if (kind === 'send') return openSend(w);
			}

			async function openReceive(w) {
				openModal(`
					<h3>Receive ${w.chain === 'solana' ? 'Solana' : 'EVM'}</h3>
					<p class="sub">Send tokens to this address from any wallet or exchange.</p>
					<div class="qr-wrap">
						<canvas id="qr-canvas" width="220" height="220"></canvas>
						<div class="qr-addr">${escapeHtml(w.address)}</div>
						<button class="btn sec sm" id="qr-copy">Copy address</button>
					</div>
					<div class="modal-actions">
						<button class="btn ghost" id="modal-close">Done</button>
					</div>
				`, async () => {
					$('modal-close').onclick = closeModal;
					$('qr-copy').onclick = () => navigator.clipboard.writeText(w.address);
					try {
						const mod = await loadCdnModule('https://esm.sh/[email protected]');
						const QR = mod.default ?? mod;
						await QR.toCanvas($('qr-canvas'), w.address, { width: 220, margin: 1, color: { dark: '#000', light: '#ffffff' } });
					} catch (err) {
						// No QR code, but the address above it is the actual payload
						// and is still readable and copyable, so the modal stays
						// usable and explains what is missing.
						const canvas = $('qr-canvas');
						const note = document.createElement('p');
						note.className = 'sub';
						note.style.cssText = 'max-width:220px;text-align:center;margin:0';
						note.textContent = `${err?.message || 'The QR code library could not be loaded.'} Copy the address below instead.`;
						canvas.replaceWith(note);
					}
				});
			}

			function openSend(w) {
				const assets = [{ value: 'native', label: w.native?.symbol || (w.chain === 'solana' ? 'SOL' : 'ETH') }];
				for (const t of w.tokens || []) {
					const id = t.mint || t.contract;
					if (id) assets.push({ value: id, label: t.symbol });
				}
				const placeholder = w.chain === 'solana' ? 'Solana address or yourname.sol' : '0x…';
				openModal(`
					<h3>Send from ${escapeHtml(w.agent_name)}</h3>
					<p class="sub">${chainLabel(w.chain, w.chain_id)} · ${shortAddr(w.address)}</p>
					<form id="send-form" autocomplete="off">
						<label><span>Asset</span>
							<select name="asset">${assets.map((a) => `<option value="${escapeHtml(a.value)}">${escapeHtml(a.label)}</option>`).join('')}</select>
						</label>
						<label><span>Recipient${w.chain === 'solana' ? ' address or .sol name' : ' address'}</span>
							<input name="recipient" data-mono required placeholder="${escapeHtml(placeholder)}" autocomplete="off" spellcheck="false" />
							<small id="recipient-resolved" style="display:none;margin-top:6px;font-family:ui-monospace,monospace;font-size:11.5px;word-break:break-all;display:block"></small>
						</label>
						<label><span>Amount</span>
							<input name="amount" inputmode="decimal" required placeholder="0.0" pattern="[0-9]*\\.?[0-9]*" autocomplete="off" />
						</label>
						<div class="modal-actions">
							<button type="button" class="btn ghost" id="modal-cancel">Cancel</button>
							<button type="submit" class="btn primary">Send</button>
						</div>
						<p id="send-err" style="color:#ff9a9a;display:none;margin-top:10px;font-size:13px"></p>
					</form>
				`, () => {
					$('modal-cancel').onclick = closeModal;
					const form = $('send-form');
					form.addEventListener('submit', (e) => onSendSubmit(e, w));
					if (w.chain === 'solana') {
						const input = form.querySelector('input[name="recipient"]');
						const status = $('recipient-resolved');
						attachSnsTypeahead(input, status);
					}
				});
			}

			// .sol name typeahead
			const SOL_NAME_RE = /^[a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63})*(?:\.sol)?$/i;
			const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
			function attachSnsTypeahead(input, status) {
				let seq = 0;
				function setStatus(kind, text) {
					status.style.display = text ? '' : 'none';
					status.textContent = text || '';
					status.style.color = kind === 'ok' ? '#7be07b' : kind === 'warn' ? '#ff9a9a' : 'var(--muted)';
				}
				async function lookup(name) {
					const myId = ++seq;
					try {
						const r = await fetch(`/api/sns?name=${encodeURIComponent(name)}`);
						if (myId !== seq) return;
						if (r.status === 404) { setStatus('warn', `${name} does not resolve`); return; }
						if (!r.ok) {
							const j = await r.json().catch(() => ({}));
							setStatus('warn', j.error_description || `Lookup failed (${r.status})`);
							return;
						}
						const { data } = await r.json();
						if (myId !== seq) return;
						setStatus('ok', `→ ${data.address}`);
					} catch (err) {
						if (myId === seq) setStatus('warn', err.message || 'Lookup failed');
					}
				}
				input.addEventListener('input', () => {
					const raw = input.value.trim();
					seq++;
					if (!raw) { setStatus('', ''); return; }
					if (SOL_ADDR_RE.test(raw)) { setStatus('', ''); return; }
					if (/\.sol$/i.test(raw) || (SOL_NAME_RE.test(raw) && !SOL_ADDR_RE.test(raw))) {
						setStatus('', 'Resolving .sol…');
						const myId = seq;
						setTimeout(() => { if (myId === seq) lookup(raw); }, 300);
						return;
					}
					setStatus('warn', 'Not a valid Solana address or .sol name');
				});
			}

			async function onSendSubmit(e, w) {
				e.preventDefault();
				const f = e.target;
				const asset = f.asset.value;
				const recipient = f.recipient.value.trim();
				const amount = f.amount.value.trim();
				const submit = f.querySelector('button[type="submit"]');
				const errEl = $('send-err');
				submit.disabled = true;
				errEl.style.display = 'none';
				try {
					const token = await getCsrf();
					const r = await fetch(`${apiUrl}/portfolio/send`, {
						method: 'POST',
						credentials: 'include',
						headers: { 'content-type': 'application/json', 'x-csrf-token': token },
						body: JSON.stringify({ agent_id: w.agent_id, chain: w.chain, asset, recipient, amount }),
					});
					const d = await r.json();
					if (!r.ok) throw new Error(d.error_description || 'Send failed');
					csrfToken = null;
					closeModal();
					await refresh({ snapshot: true });
				} catch (err) {
					errEl.textContent = err.message;
					errEl.style.display = 'block';
					csrfToken = null;
				} finally {
					submit.disabled = false;
				}
			}

			// ── Page lifecycle ────────────────────────────────────────────────

			function bindRangeTabs() {
				$('range-tabs').addEventListener('click', (e) => {
					const btn = e.target.closest('.range-tab');
					if (!btn) return;
					activeDays = parseInt(btn.dataset.days, 10);
					document.querySelectorAll('.range-tab').forEach((b) => b.removeAttribute('aria-pressed'));
					btn.setAttribute('aria-pressed', 'true');
					if (currentSummary) renderChart(currentHistory, currentSummary.total_usd);
				});
			}

			async function refresh({ snapshot = true } = {}) {
				setError('');
				const btn = $('refresh-btn');
				btn.disabled = true;
				btn.textContent = 'Loading…';
				try {
					const [summary, history] = await Promise.all([
						loadSummary({ snapshot }),
						loadHistory(activeDays || 365),
					]);
					currentSummary = summary;
					currentHistory = [...history];
					if (snapshot || !history.length) {
						currentHistory.push({ t: summary.captured_at, usd: summary.total_usd });
					}
					renderTotal(summary);
					renderHoldings(summary);
					renderWallets(summary);
					await renderChart(currentHistory, summary.total_usd);
				} catch (err) {
					setError(err.message);
				} finally {
					btn.disabled = false;
					btn.innerHTML = `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>Refresh`;
				}
			}

			(async () => {
				const me = await fetchUser();
				if (!me) return;
				renderHeaderUser($('header-user-slot'), me.user, { activePath: '/dashboard/portfolio' });
				$('refresh-btn').addEventListener('click', () => refresh({ snapshot: true }));
				bindRangeTabs();
				try {
					const [summary, history] = await Promise.all([loadSummary({ snapshot: false }), loadHistory(365)]);
					currentSummary = summary;
					currentHistory = [...history];
					if (summary.total_usd > 0) {
						const last = currentHistory[currentHistory.length - 1];
						if (!last || Math.abs(new Date(last.t).getTime() - new Date(summary.captured_at).getTime()) > 60_000) {
							currentHistory.push({ t: summary.captured_at, usd: summary.total_usd });
						}
					}
					renderTotal(summary);
					renderHoldings(summary);
					renderWallets(summary);
					await renderChart(currentHistory, summary.total_usd);
				} catch (err) {
					setError(err.message);
					$('holdings').innerHTML = '<div style="padding:20px 16px;color:var(--muted)">Failed to load holdings.</div>';
					$('wallets').innerHTML = '<div style="padding:20px 0;color:var(--muted)">Failed to load wallets.</div>';
				}
			})();
		</script>
		<script src="/brand.js" defer></script>
	<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
	<script type="module" src="/i18n.js"></script>
</body>
</html>