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.

125 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
	<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
	<meta charset="UTF-8">
		<link rel="icon" href="/favicon.ico" sizes="any" />
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
		<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
		<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
		<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
		<link rel="manifest" href="/manifest.webmanifest" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title data-i18n="pump_visualizer.meta_title">Pump.fun Visualizer · three.ws</title>
	<meta name="description" content="A real-time 3D visualization of trending tokens on Pump.fun. Each sphere is a live coin, sized by market cap." data-i18n-attr="content:pump_visualizer.meta_description">
	<link rel="canonical" href="https://three.ws/pump-visualizer">
	<link rel="stylesheet" href="/style.css">
	<link rel="stylesheet" href="/nav.css" />
	<link rel="stylesheet" href="/mobile.css" />
	<style>
		:root {
			--vz-bg: #060606;
			--vz-panel: rgba(10, 10, 10, 0.88);
			--vz-border: rgba(255, 255, 255, 0.10);
			--vz-text: var(--ink);
			--vz-muted: var(--ink-dim);
			--vz-accent: #ffffff;
			--vz-green: #34d399;
			--vz-red: var(--danger);
		}
		html, body { background: var(--vz-bg); color: var(--vz-text); overflow: hidden; height: 100%; }
		body { margin: 0; }
		.site-header { position: relative; z-index: 20; background: rgba(0, 0, 0, 0.85); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); }

		#vz-stage {
			position: fixed;
			inset: 0;
			z-index: 0;
		}
		#vz-canvas-host {
			position: absolute;
			inset: 0;
		}
		#vz-canvas-host canvas {
			display: block;
			width: 100% !important;
			height: 100% !important;
			cursor: grab;
		}
		#vz-canvas-host canvas:active { cursor: grabbing; }
		#vz-canvas-host.is-pointing canvas { cursor: pointer; }

		.vz-overlay {
			position: absolute;
			pointer-events: none;
			z-index: 10;
		}
		.vz-overlay > * { pointer-events: auto; }

		/* ── Top status bar ───────────────────────────── */
		.vz-status {
			top: calc(var(--header-h, 3.5rem) + 12px);
			left: 16px;
			display: flex;
			align-items: center;
			gap: 10px;
			background: var(--vz-panel);
			border: 1px solid var(--vz-border);
			border-radius: 10px;
			padding: 8px 14px;
			font-family: var(--font-mono);
			font-size: 12px;
			letter-spacing: 0.04em;
			color: var(--vz-text);
		}
		.vz-status .dot {
			width: 8px; height: 8px; border-radius: 50%;
			background: #555; box-shadow: 0 0 8px rgba(0,0,0,0.4);
		}
		.vz-status[data-state="loading"] .dot { background: #f59e0b; animation: vzPulse 1.2s ease-in-out infinite; }
		.vz-status[data-state="ready"] .dot { background: var(--vz-green); box-shadow: 0 0 10px rgba(52, 211, 153, 0.7); }
		.vz-status[data-state="error"] .dot { background: var(--vz-red); }
		@keyframes vzPulse {
			0%, 100% { opacity: 0.4; }
			50% { opacity: 1; }
		}
		.vz-status button {
			background: transparent;
			border: 1px solid var(--vz-border);
			color: var(--vz-text);
			border-radius: 6px;
			padding: 4px 10px;
			font: inherit;
			cursor: pointer;
			margin-left: 4px;
		}
		.vz-status button:hover { background: var(--accent-soft); }
		.vz-status button:disabled { opacity: 0.5; cursor: not-allowed; }
		.vz-status .sep { width: 1px; height: 14px; background: rgba(255,255,255,0.1); margin: 0 4px; }
		.vz-status .stat { color: var(--vz-muted); display: flex; align-items: center; gap: 6px; }
		.vz-status .stat b { color: var(--vz-text); font-weight: 600; }
		.vz-status .countdown {
			color: var(--vz-muted); font-variant-numeric: tabular-nums;
			min-width: 28px; text-align: right;
		}

		/* ── Controls panel (search + sort) ──────────────── */
		.vz-controls {
			top: calc(var(--header-h, 3.5rem) + 12px);
			left: 50%;
			transform: translateX(-50%);
			display: flex;
			gap: 8px;
			align-items: center;
			flex-wrap: wrap;
			justify-content: center;
			max-width: calc(100vw - 32px);
			background: var(--vz-panel);
			border: 1px solid var(--vz-border);
			border-radius: 10px;
			padding: 6px;
			font-family: var(--font-mono);
			font-size: 12px;
		}
		/* Screen-reader-only text: the page heading and the search field's label.
		   The stage is a full-bleed canvas with no room for visible chrome, but a
		   heading and a labelled input are not optional. */
		.vz-sr-only {
			position: absolute;
			width: 1px; height: 1px;
			padding: 0; margin: -1px;
			overflow: hidden;
			clip: rect(0 0 0 0);
			clip-path: inset(50%);
			white-space: nowrap;
			border: 0;
		}
		.vz-search {
			position: relative;
			display: flex;
			align-items: center;
		}
		.vz-search input {
			background: rgba(0,0,0,0.4);
			border: 1px solid rgba(255,255,255,0.08);
			color: var(--vz-text);
			border-radius: 6px;
			padding: 6px 10px 6px 28px;
			font: inherit;
			width: 180px;
			outline: none;
			transition: border-color var(--duration-fast), width var(--duration-base);
		}
		.vz-search input:focus {
			border-color: var(--vz-accent);
			width: 220px;
		}
		.vz-search input::placeholder { color: var(--vz-muted); }
		.vz-search::before {
			content: '';
			position: absolute;
			left: 10px; top: 50%;
			width: 12px; height: 12px;
			border: 1.5px solid var(--vz-muted);
			border-radius: 50%;
			transform: translateY(-65%);
			pointer-events: none;
		}
		.vz-search::after {
			content: '';
			position: absolute;
			left: 19px; top: 50%;
			width: 6px; height: 1.5px;
			background: var(--vz-muted);
			transform: translateY(2px) rotate(45deg);
			pointer-events: none;
		}
		.vz-mode {
			display: flex;
			gap: 0;
			padding: 2px;
			border-radius: 8px;
			background: rgba(0,0,0,0.35);
			border: 1px solid rgba(255,255,255,0.06);
			margin-right: 2px;
		}
		.vz-mode button {
			background: transparent;
			border: 1px solid transparent;
			color: var(--vz-muted);
			border-radius: 6px;
			padding: 5px 11px;
			font: inherit;
			cursor: pointer;
			letter-spacing: 0.06em;
			text-transform: uppercase;
			font-size: 10px;
			font-weight: 600;
			display: inline-flex;
			align-items: center;
			gap: 5px;
		}
		.vz-mode button:hover { color: var(--vz-text); }
		.vz-mode button.is-active {
			background: rgba(255, 255, 255, 0.22);
			color: var(--vz-text);
			border-color: var(--vz-border);
		}
		.vz-mode button[data-mode="feed"] .live-dot {
			width: 6px; height: 6px; border-radius: 50%;
			background: var(--vz-red);
			box-shadow: 0 0 6px rgba(248, 113, 113, 0.85);
		}
		.vz-mode button[data-mode="feed"].is-active {
			background: rgba(248, 113, 113, 0.18);
			color: var(--vz-text);
			border-color: rgba(248, 113, 113, 0.45);
		}
		.vz-mode button[data-mode="feed"].is-active .live-dot {
			animation: vzPulse 1.2s ease-in-out infinite;
		}
		.vz-mode button[data-mode="migrations"] .live-dot {
			width: 6px; height: 6px; border-radius: 50%;
			background: var(--vz-green);
			box-shadow: 0 0 6px rgba(52, 211, 153, 0.85);
		}
		.vz-mode button[data-mode="migrations"].is-active {
			background: rgba(52, 211, 153, 0.18);
			color: var(--vz-text);
			border-color: rgba(52, 211, 153, 0.45);
		}
		.vz-mode button[data-mode="migrations"].is-active .live-dot {
			animation: vzPulse 1.2s ease-in-out infinite;
		}
		.vz-sort {
			display: flex;
			gap: 2px;
			border-left: 1px solid rgba(255,255,255,0.08);
			padding-left: 8px;
			margin-left: 2px;
		}
		.vz-controls[data-mode="feed"] .vz-sort { display: none; }
		.vz-controls[data-mode="migrations"] .vz-sort { display: none; }
		.vz-status[data-mode="feed"] #vz-refresh { display: none; }
		.vz-status[data-mode="migrations"] #vz-refresh { display: none; }
		.vz-status[data-mode="feed"][data-state="ready"] .dot { background: var(--vz-red); box-shadow: 0 0 10px rgba(248,113,113,0.7); animation: vzPulse 1.2s ease-in-out infinite; }
		.vz-status[data-mode="migrations"][data-state="ready"] .dot { background: var(--vz-green); box-shadow: 0 0 10px rgba(52,211,153,0.7); animation: vzPulse 1.2s ease-in-out infinite; }
		.vz-status[data-mode="feed"] #vz-stat-mcap-wrap { display: none !important; }
		.vz-status[data-mode="migrations"] #vz-stat-mcap-wrap { display: none !important; }
		.vz-status[data-mode="trending"] #vz-stat-rate-wrap { display: none !important; }
		.vz-sort button {
			background: transparent;
			border: 1px solid transparent;
			color: var(--vz-muted);
			border-radius: 6px;
			padding: 5px 10px;
			font: inherit;
			cursor: pointer;
			letter-spacing: 0.04em;
			text-transform: uppercase;
			font-size: 10px;
		}
		.vz-sort button:hover { color: var(--vz-text); }
		.vz-sort button.is-active {
			background: rgba(255, 255, 255, 0.18);
			border-color: var(--vz-border);
			color: var(--vz-text);
		}

		/* ── Render-style toggle (Coins ⟷ Orbs) — visible in every mode ── */
		.vz-style {
			display: flex;
			gap: 0;
			padding: 2px;
			border-radius: 8px;
			background: rgba(0, 0, 0, 0.35);
			border: 1px solid rgba(255, 255, 255, 0.06);
			margin-left: 2px;
		}
		.vz-style button {
			background: transparent;
			border: 1px solid transparent;
			color: var(--vz-muted);
			border-radius: 6px;
			padding: 5px 10px;
			font: inherit;
			cursor: pointer;
			letter-spacing: 0.06em;
			text-transform: uppercase;
			font-size: 10px;
			font-weight: 600;
			display: inline-flex;
			align-items: center;
			gap: 5px;
		}
		.vz-style button .ico { width: 11px; height: 11px; flex-shrink: 0; opacity: 0.85; }
		.vz-style button:hover { color: var(--vz-text); }
		.vz-style button.is-active {
			background: rgba(255, 255, 255, 0.22);
			border-color: var(--vz-border);
			color: var(--vz-text);
		}
		.vz-style button:focus-visible { outline: 2px solid var(--vz-accent); outline-offset: 1px; }

		/* ── Cross-links to sibling launchpad surfaces ──── */
		.vz-links {
			display: flex;
			gap: 12px;
			align-items: center;
			border-left: 1px solid rgba(255, 255, 255, 0.08);
			padding-left: 8px;
			margin-left: 2px;
		}
		.vz-links a {
			color: var(--vz-muted);
			text-decoration: none;
			font-size: 10px;
			letter-spacing: 0.04em;
			text-transform: uppercase;
			white-space: nowrap;
			transition: color var(--duration-fast);
		}
		.vz-links a:hover { color: var(--vz-text); }
		.vz-links a:focus-visible {
			outline: 1px solid var(--vz-accent);
			outline-offset: 2px;
			border-radius: 4px;
		}

		/* ── Help / hint ──────────────────────────────── */
		.vz-hint {
			top: calc(var(--header-h, 3.5rem) + 12px);
			right: 16px;
			background: var(--vz-panel);
			border: 1px solid rgba(255, 255, 255, 0.08);
			border-radius: 10px;
			padding: 8px 12px;
			font-family: var(--font-mono);
			font-size: 11px;
			color: var(--vz-muted);
			max-width: 240px;
			line-height: 1.6;
		}
		.vz-hint b { color: var(--vz-text); font-weight: 600; }

		/* ── Hover tooltip (follows cursor) ───────────── */
		.vz-tooltip {
			position: fixed;
			z-index: 15;
			pointer-events: none;
			background: rgba(0, 0, 0, 0.95);
			border: 1px solid var(--vz-border);
			border-radius: 8px;
			padding: 8px 12px;
			font-family: var(--font-mono);
			font-size: 12px;
			color: var(--vz-text);
			transform: translate(12px, 12px);
			opacity: 0;
			transition: opacity var(--duration-fast) var(--ease-standard);
			white-space: nowrap;
		}
		.vz-tooltip.is-visible { opacity: 1; }
		.vz-tooltip .name { color: var(--vz-accent); font-weight: 600; }
		.vz-tooltip .mcap { color: var(--vz-green); }

		/* ── Detail panel ─────────────────────────────── */
		.vz-detail {
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0;
			width: 360px;
			max-width: 90vw;
			background: var(--vz-panel);
			border-left: 1px solid var(--vz-border);
			backdrop-filter: blur(12px);
			-webkit-backdrop-filter: blur(12px);
			padding: calc(var(--header-h, 3.5rem) + 20px) 20px 20px;
			overflow-y: auto;
			transform: translateX(100%);
			transition: transform var(--duration-base) var(--ease-standard);
			display: flex;
			flex-direction: column;
			gap: 14px;
		}
		.vz-detail.is-open { transform: translateX(0); }
		.vz-detail .close {
			position: absolute;
			top: calc(var(--header-h, 3.5rem) + 12px);
			right: 12px;
			width: 28px; height: 28px;
			border: 1px solid rgba(255,255,255,0.15);
			background: rgba(255,255,255,0.04);
			color: var(--vz-text);
			border-radius: 50%;
			cursor: pointer;
			font-size: 16px;
			line-height: 1;
		}
		.vz-detail .close:hover { background: var(--accent-soft); }
		.vz-detail .head { display: flex; align-items: center; gap: 12px; }
		.vz-detail .avatar {
			width: 56px; height: 56px; border-radius: 50%;
			background: #111; border: 1px solid var(--vz-border);
			object-fit: cover; flex-shrink: 0;
		}
		.vz-detail .title { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
		.vz-detail .title .name {
			font-family: var(--font-display);
			font-size: 18px; font-weight: 600;
			color: var(--vz-text);
			overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
		}
		.vz-detail .title .symbol {
			font-family: var(--font-mono);
			font-size: 13px; color: var(--vz-accent);
		}
		.vz-detail .stats {
			display: grid; grid-template-columns: 1fr 1fr; gap: 10px;
			padding: 12px; border-radius: 8px;
			background: rgba(255,255,255,0.03);
			border: 1px solid rgba(255,255,255,0.06);
		}
		.vz-detail .stat .label {
			font-family: var(--font-mono);
			font-size: 10px; letter-spacing: 0.08em;
			color: var(--vz-muted); text-transform: uppercase;
		}
		.vz-detail .stat .value {
			font-family: var(--font-mono);
			font-size: 14px; color: var(--vz-text); margin-top: 2px;
		}
		.vz-detail .stat .value.green { color: var(--vz-green); }
		.vz-detail .description {
			font-size: 13px; line-height: 1.55; color: var(--vz-muted);
			max-height: 140px; overflow-y: auto;
			padding: 10px; border-radius: 8px;
			background: rgba(255,255,255,0.02);
			border: 1px solid rgba(255,255,255,0.05);
		}
		.vz-detail .description:empty { display: none; }
		/* ── Extra real-data rows (creator track record, from-ATH, liquidity) ── */
		.vz-detail .vz-extra { display: flex; flex-direction: column; gap: 8px; }
		.vz-detail .vz-extra:empty { display: none; }
		.vz-detail .meta-row {
			display: flex; align-items: center; gap: 10px;
			padding: 9px 11px; border-radius: 8px;
			background: rgba(255, 255, 255, 0.03);
			border: 1px solid rgba(255, 255, 255, 0.06);
			font-family: var(--font-mono); font-size: 12px;
		}
		.vz-detail .meta-row .k {
			color: var(--vz-muted); text-transform: uppercase;
			letter-spacing: 0.06em; font-size: 10px;
		}
		.vz-detail .meta-row .v { color: var(--vz-text); margin-left: auto; text-align: right; }
		.vz-detail .meta-row a.v { color: var(--vz-accent); text-decoration: none; }
		.vz-detail .meta-row a.v:hover { text-decoration: underline; }
		.vz-detail .meta-row .v .good { color: var(--vz-green); }
		.vz-detail .meta-row .v .bad { color: var(--vz-red); }
		.vz-detail .meta-row .v .dim { color: var(--vz-muted); }
		.vz-detail .mint {
			font-family: var(--font-mono);
			font-size: 11px; color: var(--vz-muted);
			word-break: break-all;
			padding: 8px 10px;
			background: rgba(0,0,0,0.4);
			border: 1px solid rgba(255,255,255,0.05);
			border-radius: 6px;
		}
		.vz-detail .links { display: flex; flex-wrap: wrap; gap: 6px; }
		.vz-detail .links a,
		.vz-detail .links button {
			display: inline-flex; align-items: center; gap: 4px;
			padding: 6px 10px; font-size: 12px;
			border-radius: 6px;
			border: 1px solid var(--vz-border);
			color: var(--vz-text);
			text-decoration: none;
			background: rgba(255, 255, 255, 0.08);
			font: inherit; line-height: 1; cursor: pointer;
			transition: background var(--duration-fast), transform var(--duration-fast), box-shadow var(--duration-fast);
		}
		.vz-detail .links a:hover,
		.vz-detail .links button:hover { background: var(--accent-soft); }
		.vz-detail .links a:focus-visible,
		.vz-detail .links button:focus-visible { outline: 2px solid var(--vz-accent); outline-offset: 2px; }
		.vz-detail .links a.primary,
		.vz-detail .links button.primary {
			background: var(--vz-accent); color: #fff; border-color: var(--vz-accent);
			font-weight: 600;
		}
		.vz-detail .links button.primary:hover {
			background: var(--vz-accent); transform: translateY(-1px);
			box-shadow: 0 0 18px rgba(255, 255, 255, 0.35);
		}
		.vz-detail .links button.primary:disabled { opacity: 0.6; cursor: default; transform: none; box-shadow: none; }
		.vz-detail .live-badge {
			display: inline-flex; align-items: center; gap: 6px;
			padding: 3px 8px; font-size: 10px; letter-spacing: 0.06em;
			text-transform: uppercase;
			background: rgba(248, 113, 113, 0.15);
			color: var(--vz-red);
			border: 1px solid rgba(248, 113, 113, 0.4);
			border-radius: 20px;
			margin-top: 4px;
			width: max-content;
		}
		.vz-detail .live-badge::before {
			content: ''; width: 6px; height: 6px; border-radius: 50%;
			background: var(--vz-red); animation: vzPulse 1.2s ease-in-out infinite;
		}
		.vz-detail .live-badge.is-grad {
			background: rgba(52, 211, 153, 0.15);
			color: var(--vz-green);
			border-color: rgba(52, 211, 153, 0.4);
		}
		.vz-detail .live-badge.is-grad::before { background: var(--vz-green); }

		/* ── Oracle conviction badge in detail panel ───── */
		.vz-oracle { display: flex; align-items: center; gap: 8px; padding: 10px 12px; background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.07); border-radius: 8px; margin: 10px 0 0; text-decoration: none; color: inherit; transition: background var(--duration-fast); }
		.vz-oracle:hover { background: rgba(255,255,255,0.07); }
		.vz-oracle-label { font-size: 10px; text-transform: uppercase; letter-spacing: .07em; color: var(--vz-muted); }
		.vz-oracle-score { font-size: 22px; font-weight: 700; line-height: 1; }
		.vz-oracle-tier { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .05em; }
		.vz-oracle-sk { height: 42px; background: rgba(255,255,255,0.06); border-radius: 8px; margin: 10px 0 0; animation: vzPulse 1.4s ease-in-out infinite; }

		/* ── Legend (bottom-left rank list) ───────────── */
		.vz-legend {
			bottom: 16px;
			left: 16px;
			background: var(--vz-panel);
			border: 1px solid rgba(255,255,255,0.08);
			border-radius: 10px;
			padding: 10px 12px;
			max-height: 260px;
			overflow-y: auto;
			width: 280px;
			font-family: var(--font-mono);
			font-size: 12px;
		}
		.vz-legend .head {
			color: var(--vz-muted);
			font-size: 10px; letter-spacing: 0.1em;
			text-transform: uppercase;
			padding-bottom: 6px; margin-bottom: 6px;
			border-bottom: 1px solid rgba(255,255,255,0.06);
		}
		.vz-legend ol { list-style: none; padding: 0; margin: 0; }
		.vz-legend li {
			display: flex; align-items: center; gap: 8px;
			padding: 4px 2px; border-radius: 4px;
			cursor: pointer;
			color: var(--vz-text);
		}
		.vz-legend li:hover { background: rgba(255,255,255,0.04); }
		.vz-legend li:focus-visible { outline: 2px solid var(--focus-ring-color); outline-offset: 2px; }
		.vz-legend li.is-selected { background: var(--accent-soft); }
		.vz-legend li .rank { color: var(--vz-muted); width: 26px; font-size: 10px; font-variant-numeric: tabular-nums; }
		.vz-legend li .rank.age { color: var(--vz-red); font-weight: 600; }
		.vz-legend li .sym { color: var(--vz-accent); font-size: 11px; }
		.vz-legend li .name {
			flex: 1; min-width: 0;
			overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
		}
		.vz-legend li .thumb {
			width: 18px; height: 18px;
			border-radius: 50%;
			background: #111;
			object-fit: cover;
			flex-shrink: 0;
			border: 1px solid rgba(255,255,255,0.06);
		}
		.vz-legend li .mc {
			color: var(--vz-green);
			font-size: 10px;
			margin-left: auto;
			padding-left: 6px;
		}
		/* Live equalizer — three bouncing bars + LIVE pill */
		.vz-eq {
			display: inline-flex;
			align-items: flex-end;
			gap: 2px;
			height: 12px;
			margin-left: 4px;
			flex-shrink: 0;
		}
		.vz-eq span {
			display: block;
			width: 2px;
			background: var(--vz-red);
			border-radius: 1px;
			box-shadow: 0 0 4px rgba(248, 113, 113, 0.75);
			animation: vzEqBounce 0.9s ease-in-out infinite;
			transform-origin: bottom;
		}
		.vz-eq span:nth-child(1) { height: 60%; animation-delay: -0.10s; }
		.vz-eq span:nth-child(2) { height: 100%; animation-delay: -0.45s; }
		.vz-eq span:nth-child(3) { height: 75%; animation-delay: -0.25s; }
		.vz-eq span:nth-child(4) { height: 45%; animation-delay: -0.60s; }
		@keyframes vzEqBounce {
			0%, 100% { transform: scaleY(0.30); }
			50%      { transform: scaleY(1.00); }
		}
		.vz-live-pill {
			display: inline-flex;
			align-items: center;
			gap: 4px;
			font-size: 9px;
			letter-spacing: 0.08em;
			color: var(--vz-red);
			text-transform: uppercase;
			padding: 1px 5px;
			border: 1px solid rgba(248, 113, 113, 0.45);
			background: rgba(248, 113, 113, 0.12);
			border-radius: 999px;
			margin-left: 4px;
			flex-shrink: 0;
		}
		.vz-legend li.is-live .mc { color: var(--vz-red); }
		.vz-legend.is-empty::after {
			content: 'No matches';
			display: block;
			text-align: center;
			color: var(--vz-muted);
			font-size: 11px;
			padding: 18px 8px;
		}

		/* ── WebGL-unavailable fallback ─────────────────
		   No usable 3D context → the legend becomes the primary, full-height list
		   surface and a banner explains why. Never a blank canvas. */
		.vz-fallback {
			top: calc(var(--header-h, 3.5rem) + 56px);
			left: 50%;
			transform: translateX(-50%);
			max-width: min(620px, calc(100vw - 32px));
			display: flex;
			align-items: flex-start;
			gap: 10px;
			background: rgba(20, 12, 8, 0.92);
			border: 1px solid rgba(245, 158, 11, 0.4);
			border-radius: 10px;
			padding: 12px 14px;
			color: var(--vz-text);
			font-size: 12.5px;
			line-height: 1.45;
			box-shadow: 0 10px 30px rgba(0,0,0,0.5);
		}
		.vz-fallback .icon { color: #f59e0b; font-size: 16px; line-height: 1.2; flex-shrink: 0; }
		.vz-fallback .body b { color: #fcd34d; }
		.vz-fallback button {
			margin-top: 8px;
			background: transparent;
			border: 1px solid var(--vz-border);
			color: var(--vz-text);
			border-radius: 6px;
			padding: 5px 10px;
			font: inherit;
			font-size: 11px;
			cursor: pointer;
		}
		.vz-fallback button:hover { background: var(--accent-soft); }
		body.vz-no-webgl #vz-canvas-host { display: none; }
		body.vz-no-webgl .vz-intro { display: none; }
		body.vz-no-webgl .vz-ramp { display: none; }
		body.vz-no-webgl .vz-legend {
			top: calc(var(--header-h, 3.5rem) + 132px);
			bottom: 16px;
			left: 50%;
			transform: translateX(-50%);
			width: min(620px, calc(100vw - 32px));
			max-height: none;
		}
		body.vz-no-webgl .vz-legend li { padding: 8px 6px; }
		body.vz-no-webgl .vz-legend li .thumb { width: 26px; height: 26px; }

		/* ── Market-cap tier key (bottom-right) ───────── */
		.vz-ramp {
			bottom: 16px;
			right: 16px;
			background: var(--vz-panel);
			border: 1px solid rgba(255, 255, 255, 0.08);
			border-radius: 10px;
			padding: 10px 12px;
			width: 172px;
			font-family: var(--font-mono);
			font-size: 11px;
		}
		.vz-ramp .head {
			color: var(--vz-muted);
			font-size: 10px; letter-spacing: 0.1em;
			text-transform: uppercase;
			padding-bottom: 6px; margin-bottom: 6px;
			border-bottom: 1px solid rgba(255, 255, 255, 0.06);
		}
		.vz-ramp .tier {
			display: flex; align-items: center; gap: 8px;
			padding: 3px 0;
			color: var(--vz-muted);
		}
		.vz-ramp .tier .sw {
			width: 10px; height: 10px; border-radius: 3px;
			flex-shrink: 0;
		}
		.vz-ramp .tier .nm { color: var(--vz-text); }
		.vz-ramp .tier .th {
			margin-left: auto;
			font-variant-numeric: tabular-nums;
		}
		.vz-ramp .move {
			display: flex; gap: 12px;
			margin-top: 8px; padding-top: 8px;
			border-top: 1px solid rgba(255, 255, 255, 0.06);
			color: var(--vz-muted);
		}
		.vz-ramp .move b { font-weight: 600; }
		.vz-ramp .move .up b { color: var(--vz-green); }
		.vz-ramp .move .down b { color: var(--vz-red); }

		/* ── Intro / loading overlay ──────────────────── */
		.vz-intro {
			position: absolute;
			inset: 0;
			z-index: 12;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			background: radial-gradient(ellipse at center, rgba(255, 255, 255, 0.08) 0%, var(--vz-bg) 70%);
			pointer-events: none;
			opacity: 1;
			transition: opacity var(--duration-slow) var(--ease-standard) var(--duration-base);
		}
		.vz-intro.is-hidden { opacity: 0; }
		.vz-intro .ring {
			width: 56px; height: 56px;
			border-radius: 50%;
			border: 2px solid rgba(255, 255, 255, 0.18);
			border-top-color: var(--vz-accent);
			animation: vzSpin 1s linear infinite;
		}
		.vz-intro .label {
			margin-top: 18px;
			font-family: var(--font-mono);
			font-size: 12px;
			letter-spacing: 0.18em;
			color: var(--vz-muted);
			text-transform: uppercase;
		}
		@keyframes vzSpin {
			to { transform: rotate(360deg); }
		}

		/* ── Hint (dismissible) ───────────────────────── */
		.vz-hint button.dismiss {
			background: transparent;
			border: none;
			color: var(--vz-muted);
			font: inherit;
			cursor: pointer;
			margin-left: 8px;
			padding: 0;
			opacity: 0.6;
		}
		.vz-hint button.dismiss:hover { opacity: 1; color: var(--vz-text); }
		.vz-hint.is-hidden { display: none; }

		/* ── Error overlay ────────────────────────────── */
		.vz-error {
			position: absolute;
			top: 50%; left: 50%;
			transform: translate(-50%, -50%);
			background: var(--vz-panel);
			border: 1px solid rgba(248, 113, 113, 0.4);
			border-radius: 10px;
			padding: 20px 28px;
			text-align: center;
			max-width: 360px;
		}
		.vz-error h3 { margin: 0 0 8px; color: var(--vz-red); font-family: var(--font-display); }
		.vz-error p { margin: 0 0 14px; color: var(--vz-muted); font-size: 13px; }
		.vz-error button {
			background: var(--vz-accent);
			color: #fff;
			border: none;
			border-radius: 6px;
			padding: 8px 18px;
			font: inherit;
			cursor: pointer;
		}

		@media (max-width: 860px) {
			.vz-controls { left: 16px; right: 16px; transform: none; }
			.vz-search input { width: 100%; }
			.vz-search input:focus { width: 100%; }
		}
		@media (max-width: 720px) {
			.vz-hint { display: none; }
			.vz-ramp { display: none; }
			.vz-legend { width: 200px; max-height: 180px; bottom: 12px; left: 12px; }
			.vz-detail { width: 100%; }
			.vz-status .stat { display: none; }
			.vz-controls { top: calc(var(--header-h, 3.5rem) + 60px); }
			.vz-sort { display: none; }
		}
	</style>

	<meta property="og:type" content="website">
	<meta property="og:site_name" content="three.ws">
	<meta property="og:title" content="Pump Visualizer · three.ws" data-i18n-attr="content:pump_visualizer.meta_og_title">
	<meta property="og:description" content="3D visualizer of trending pump.fun tokens: live market data rendered as an interactive scene." data-i18n-attr="content:pump_visualizer.meta_og_description">
	<meta property="og:url" content="https://three.ws/pump-visualizer">
	<meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Pump+Visualizer&amp;d=3D+visualizer+of+trending+pump.fun+tokens%3A+live+market+data+rendered+as+an+interactive+scene.&amp;p=%2Fpump-visualizer">
	<meta property="og:image:width" content="1200">
	<meta property="og:image:height" content="630">
	<meta name="twitter:card" content="summary_large_image">
	<meta name="twitter:title" content="Pump Visualizer · three.ws" data-i18n-attr="content:pump_visualizer.meta_twitter_title">
	<meta name="twitter:description" content="3D visualizer of trending pump.fun tokens: live market data rendered as an interactive scene." data-i18n-attr="content:pump_visualizer.meta_twitter_description">
	<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Pump+Visualizer&amp;d=3D+visualizer+of+trending+pump.fun+tokens%3A+live+market+data+rendered+as+an+interactive+scene.&amp;p=%2Fpump-visualizer">
	<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Pump Visualizer","description":"3D visualizer of trending pump.fun tokens: live market data rendered as an interactive scene.","url":"https://three.ws/pump-visualizer","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>

	<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
	<meta property="og:locale" content="en_US">
	<meta property="og:image:alt" content="Pump Visualizer, three.ws">
	<meta name="twitter:site" content="@trythreews">
</head>
<body>
	<header><div id="nav-container"></div></header>
	<script src="/nav.js"></script>

	<div id="vz-stage">
		<h1 class="vz-sr-only" data-i18n="pump_visualizer.page_heading">Live 3D visualizer of pump.fun tokens</h1>
		<div id="vz-canvas-host"></div>

		<div class="vz-overlay vz-status" id="vz-status" data-state="loading" data-mode="feed" role="status" aria-live="polite">
			<span class="dot"></span>
			<span id="vz-status-text" data-i18n="pump_visualizer.connecting_to_pump_fun_firehose">Connecting to pump.fun firehose…</span>
			<span class="sep"></span>
			<span class="stat"><b id="vz-stat-count">0</b> <span data-i18n="pump_visualizer.tokens_label">tokens</span></span>
			<span class="sep"></span>
			<span class="stat" id="vz-stat-rate-wrap"><b id="vz-stat-rate"></b> <span id="vz-stat-rate-per-min" data-i18n="pump_visualizer.per_minute_label">/min</span><span id="vz-stat-rate-per-hr" data-i18n="pump_visualizer.per_hour_label" hidden>/hr</span></span>
			<span class="stat" id="vz-stat-mcap-wrap"><span data-i18n="pump_visualizer.total_label">total</span> <b id="vz-stat-mcap"></b></span>
			<button id="vz-refresh" type="button" title="Refresh data (R)" disabled data-i18n-attr="title:pump_visualizer.refresh_data_r_title">↻ <span class="countdown" id="vz-countdown">●</span></button>
		</div>

		<div class="vz-overlay vz-controls" id="vz-controls" data-mode="feed" hidden>
			<div class="vz-mode" role="tablist" aria-label="View mode">
				<button type="button" data-mode="feed" class="is-active" data-i18n-html="pump_visualizer.live_feed"><span class="live-dot"></span>Live Feed</button>
				<button type="button" data-mode="migrations" data-i18n-html="pump_visualizer.migrations"><span class="live-dot"></span>Migrations</button>
				<button type="button" data-mode="trending" data-i18n="pump_visualizer.trending">Trending</button>
			</div>
			<label class="vz-search" for="vz-search-input">
				<span class="vz-sr-only" data-i18n="pump_visualizer.search_label">Search tokens by name, symbol or mint</span>
				<input type="search" id="vz-search-input" placeholder="Search name, symbol, mint…" autocomplete="off" spellcheck="false" data-i18n-attr="placeholder:pump_visualizer.search_placeholder" />
			</label>
			<div class="vz-sort" role="tablist" aria-label="Sort tokens">
				<button type="button" data-sort="mcap" class="is-active" data-i18n="pump_visualizer.mcap">Mcap</button>
				<button type="button" data-sort="live" data-i18n="pump_visualizer.streams">Streams</button>
				<button type="button" data-sort="replies" data-i18n="pump_visualizer.replies">Replies</button>
				<button type="button" data-sort="recent" data-i18n="pump_visualizer.new">New</button>
			</div>
			<div class="vz-style" role="tablist" aria-label="Render style" title="Switch how tokens are drawn (C)">
				<button type="button" data-style="coin" aria-label="Show tokens as coin logos" data-i18n-attr="aria-label:pump_visualizer.show_tokens_as_coin_logos_arialabel">
					<svg class="ico" viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2"/><circle cx="12" cy="12" r="3.4" fill="currentColor"/></svg>Coins
				</button>
				<button type="button" data-style="orb" aria-label="Show tokens as 3D orbs" data-i18n-attr="aria-label:pump_visualizer.show_tokens_as_3d_orbs_arialabel">
					<svg class="ico" viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2"/><ellipse cx="12" cy="12" rx="9" ry="3.6" stroke="currentColor" stroke-width="1.4" opacity="0.7"/></svg>Orbs
				</button>
			</div>
			<nav class="vz-links" aria-label="Explore the launchpad">
				<a href="/pump-live" data-i18n="pump_visualizer.feed">Feed →</a>
				<a href="/launches" data-i18n="pump_visualizer.all_launches">All launches →</a>
			</nav>
		</div>

		<div class="vz-overlay vz-hint" id="vz-hint" aria-hidden="true">
			<b data-i18n="pump_visualizer.drag">Drag</b> to rotate · <b data-i18n="pump_visualizer.scroll">Scroll</b> to zoom · <b data-i18n="pump_visualizer.click">Click</b> for details · <b data-i18n="pump_visualizer.double_click">Double-click</b> to open · <b>/</b> to search · <b data-i18n="pump_visualizer.c">C</b> coins/orbs
			<button type="button" class="dismiss" id="vz-hint-dismiss" aria-label="Dismiss" data-i18n-attr="aria-label:pump_visualizer.dismiss_arialabel">×</button>
		</div>

		<div class="vz-intro" id="vz-intro" aria-hidden="true">
			<div class="ring"></div>
			<div class="label">Loading market</div>
		</div>

		<div class="vz-overlay vz-fallback" id="vz-fallback" role="status" hidden>
			<span class="icon" aria-hidden="true">⚠</span>
			<div class="body">
				<div id="vz-fallback-text"><b data-i18n="pump_visualizer.3d_view_unavailable">3D view unavailable.</b> Your device or browser doesn't support WebGL, so we're showing the live pump.fun feed as a list below. All data is real-time.</div>
				<button type="button" id="vz-fallback-retry" data-i18n="pump_visualizer.try_3d_again">Try 3D again</button>
			</div>
		</div>

		<aside class="vz-overlay vz-legend" id="vz-legend" hidden>
			<div class="head">Top 20 by Market Cap</div>
			<ol id="vz-legend-list"></ol>
		</aside>

		<aside class="vz-overlay vz-ramp" id="vz-ramp" aria-label="Market-cap visual key" hidden>
			<div class="head">Market cap → look</div>
			<div id="vz-ramp-tiers"></div>
			<div class="move">
				<span class="up" data-i18n-html="pump_visualizer.up">▲ <b>up</b></span>
				<span class="down" data-i18n-html="pump_visualizer.down">▼ <b>down</b></span>
				<span style="margin-left:auto;color:var(--vz-muted)" data-i18n="pump_visualizer.on_refresh">on refresh</span>
			</div>
		</aside>

		<aside class="vz-overlay vz-detail" id="vz-detail" aria-hidden="true">
			<button class="close" type="button" id="vz-detail-close" aria-label="Close details" data-i18n-attr="aria-label:pump_visualizer.close_details_arialabel">×</button>
			<div class="head">
				<img class="avatar" id="vz-detail-avatar" alt="" />
				<div class="title">
					<span class="name" id="vz-detail-name"></span>
					<span class="symbol" id="vz-detail-symbol"></span>
				</div>
			</div>
			<div class="live-badge" id="vz-detail-live" hidden></div>
			<div class="stats">
				<div class="stat"><div class="label">Market cap</div><div class="value green" id="vz-detail-mcap"></div></div>
				<div class="stat"><div class="label">ATH market cap</div><div class="value" id="vz-detail-ath"></div></div>
				<div class="stat"><div class="label">Replies</div><div class="value" id="vz-detail-replies"></div></div>
				<div class="stat"><div class="label">Age</div><div class="value" id="vz-detail-age"></div></div>
			</div>
			<div class="vz-extra" id="vz-detail-extra"></div>
			<div class="description" id="vz-detail-description"></div>
			<div id="vz-oracle-slot"></div>
			<div class="mint" id="vz-detail-mint" title="Token mint address"></div>
			<div class="links" id="vz-detail-links"></div>
		</aside>

		<div class="vz-tooltip" id="vz-tooltip">
			<div class="name" id="vz-tt-name"></div>
			<div class="mcap" id="vz-tt-mcap"></div>
		</div>

		<div class="vz-error" id="vz-error" hidden>
			<h3 data-i18n="pump_visualizer.could_not_load_trending_tokens">Could not load trending tokens</h3>
			<p id="vz-error-message"></p>
			<button type="button" id="vz-error-retry" data-i18n="pump_visualizer.retry">Retry</button>
		</div>
	</div>

	<script type="module">
		import * as THREE from 'three';
		import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
		import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
		import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
		import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
		import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';

		// Every "no value yet" slot renders this one glyph. Declared as an escape
		// sequence because the literal character is banned in this repo's source.
		const NO_VALUE = '\u2014';
		const TRENDING_API = '/api/pump/trending?limit=50&rich=1';
		const LIVE_FEED_API = '/api/agents/pumpfun-feed?kind=mint';
		const MIGRATIONS_FEED_API = '/api/agents/pumpfun-feed?kind=graduation';
		const MIGRATIONS_BACKFILL_API = '/api/pump/recent-graduations?limit=20';
		const STATS_API    = '/api/pump/helius-stats';
		const SPHERE_RADIUS = 28;
		const MIN_TOKEN_R = 0.7;
		const MAX_TOKEN_R = 6.0;
		const REFRESH_INTERVAL_MS = 60_000;
		const STATS_INTERVAL_MS = 5_000;
		// SSE reconnect with exponential backoff. The server cycles the stream every
		// ~90s (a normal `close` that does NOT count as a failure); only connections
		// that never opened count toward the cap. After FEED_MAX_RECONNECT_ATTEMPTS
		// consecutive failures we stop auto-retrying and surface a manual Reconnect.
		const FEED_BASE_BACKOFF_MS = 1_500;
		const FEED_MAX_BACKOFF_MS = 60_000;
		const FEED_MAX_RECONNECT_ATTEMPTS = 8;
		const LABEL_COUNT = 3;            // always-on 3D labels for top-N
		const FLASH_DURATION_MS = 1800;   // diff-flash on refresh (trending mode)
		const FEED_CAP = 60;              // max simultaneous spheres in feed mode
		const FEED_FADE_OUT_MS = 520;     // eviction fade (ms)
		const FEED_LIVE_MIN_LOG = Math.log10(4_000);    // $4k → smallest sphere
		const FEED_LIVE_MAX_LOG = Math.log10(500_000);  // $500k+ → biggest sphere

		// ── market-cap tiers ─────────────────────────────────────────────
		// Market cap drives a coin's entire look — not just its size. As a coin's
		// cap climbs it shifts color (cool → hot), grows a crystalline wireframe
		// cage with more facets, and spins/pulses with more energy. On a trending
		// refresh, a coin that crossed into a higher tier visibly upgrades; one
		// that fell downgrades — paired with the green/red move flash below.
		const MCAP_TIERS = [
			{ name: 'Seed',     min: 0,         color: 0x3b82f6, emissive: 0x1d4ed8, cage: null,                                       spin: 0.04, pulse: 0.10, pulseRate: 0.0020 },
			{ name: 'Rising',   min: 30_000,    color: 0x6366f1, emissive: 0x4338ca, cage: { detail: 0, scale: 1.42, color: 0x818cf8 }, spin: 0.10, pulse: 0.16, pulseRate: 0.0030 },
			{ name: 'Hot',      min: 120_000,   color: 0xa855f7, emissive: 0x7e22ce, cage: { detail: 1, scale: 1.45, color: 0xc084fc }, spin: 0.18, pulse: 0.24, pulseRate: 0.0042 },
			{ name: 'Breakout', min: 600_000,   color: 0x34d399, emissive: 0x059669, cage: { detail: 2, scale: 1.48, color: 0x6ee7b7 }, spin: 0.30, pulse: 0.32, pulseRate: 0.0055 },
			{ name: 'Mega',     min: 2_500_000, color: 0xfbbf24, emissive: 0xd97706, cage: { detail: 3, scale: 1.52, color: 0xfcd34d }, spin: 0.46, pulse: 0.42, pulseRate: 0.0070 },
		];
		function tierForMcap(usd) {
			const n = Number(usd) || 0;
			let tier = MCAP_TIERS[0], index = 0;
			for (let i = 0; i < MCAP_TIERS.length; i++) {
				if (n >= MCAP_TIERS[i].min) { tier = MCAP_TIERS[i]; index = i; }
			}
			return { ...tier, index };
		}

		const host = document.getElementById('vz-canvas-host');
		const statusEl = document.getElementById('vz-status');
		const statusText = document.getElementById('vz-status-text');
		const refreshBtn = document.getElementById('vz-refresh');
		const countdownEl = document.getElementById('vz-countdown');
		const statCountEl = document.getElementById('vz-stat-count');
		const statMcapEl = document.getElementById('vz-stat-mcap');
		const statRateEl = document.getElementById('vz-stat-rate');
		statRateEl.textContent = NO_VALUE;
		statMcapEl.textContent = NO_VALUE;
		const statRatePerMinEl = document.getElementById('vz-stat-rate-per-min');
		const statRatePerHrEl = document.getElementById('vz-stat-rate-per-hr');
		// The rate unit ships as two pre-translated spans rather than a string the
		// script writes, so switching feed/migrations never drops back to English.
		function setRateUnit(perHour) {
			statRatePerMinEl.hidden = perHour;
			statRatePerHrEl.hidden = !perHour;
		}
		const controlsEl = document.getElementById('vz-controls');
		const searchInput = document.getElementById('vz-search-input');
		const sortBtns = controlsEl.querySelectorAll('.vz-sort button');
		const modeBtns = controlsEl.querySelectorAll('.vz-mode button');
		const styleBtns = controlsEl.querySelectorAll('.vz-style button');
		const legendHeadEl = document.querySelector('#vz-legend .head');
		const hintEl = document.getElementById('vz-hint');
		const hintDismiss = document.getElementById('vz-hint-dismiss');
		const introEl = document.getElementById('vz-intro');
		const tooltip = document.getElementById('vz-tooltip');
		const ttName = document.getElementById('vz-tt-name');
		const ttMcap = document.getElementById('vz-tt-mcap');
		const detailEl = document.getElementById('vz-detail');
		const detailClose = document.getElementById('vz-detail-close');
		const legendEl = document.getElementById('vz-legend');
		const legendList = document.getElementById('vz-legend-list');
		const errorEl = document.getElementById('vz-error');
		const errorMessage = document.getElementById('vz-error-message');
		const errorRetry = document.getElementById('vz-error-retry');

		// ── three.js scene ────────────────────────────────────────────
		const scene = new THREE.Scene();
		scene.background = new THREE.Color(0x05060a);
		scene.fog = new THREE.Fog(0x05060a, 80, 220);

		const camera = new THREE.PerspectiveCamera(55, 1, 0.1, 500);
		// Start far out so we can fly in once data arrives.
		camera.position.set(0, 14, 180);

		// ── WebGL capability check ────────────────────────────────────
		// Low-end / locked-down / software-blocked devices can lack a usable WebGL
		// context. Detect it up front; if the renderer can't be created we fall back
		// to a pure-DOM list view (the legend, un-capped) rather than leaving a blank
		// canvas. `webglOK` gates every GPU touchpoint below.
		function detectWebGL() {
			try {
				const test = document.createElement('canvas');
				const gl = test.getContext('webgl2') || test.getContext('webgl') || test.getContext('experimental-webgl');
				if (!gl || typeof gl.getParameter !== 'function') return false;
				if (gl.isContextLost && gl.isContextLost()) return false;
				return true;
			} catch { return false; }
		}

		let webglOK = detectWebGL();
		let renderer = null, composer = null, bloomPass = null, controls = null;

		if (webglOK) {
			try {
				renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
				renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
				renderer.outputColorSpace = THREE.SRGBColorSpace;
				renderer.toneMapping = THREE.ACESFilmicToneMapping;
				renderer.toneMappingExposure = 1.05;
				host.appendChild(renderer.domElement);

				// Post-processing — bloom gives emissive (live red, accent purple) cinematic glow.
				composer = new EffectComposer(renderer);
				composer.addPass(new RenderPass(scene, camera));
				bloomPass = new UnrealBloomPass(new THREE.Vector2(1, 1), 0.85, 0.55, 0.18);
				composer.addPass(bloomPass);
				composer.addPass(new OutputPass());

				controls = new OrbitControls(camera, renderer.domElement);
				controls.enableDamping = true;
				controls.dampingFactor = 0.06;
				controls.rotateSpeed = 0.6;
				controls.zoomSpeed = 0.7;
				controls.minDistance = 8;
				controls.maxDistance = 160;
				controls.autoRotate = true;
				controls.autoRotateSpeed = 0.35;

				// A context lost after creation (driver reset, mobile GPU recycle) would
				// otherwise freeze on the last frame — fall back to the list view.
				renderer.domElement.addEventListener('webglcontextlost', (ev) => {
					ev.preventDefault();
					enterListFallback('Your browser dropped the 3D rendering context. Showing the live list instead.');
				}, false);
			} catch (err) {
				console.warn('[pump-visualizer] WebGL renderer init failed, using list fallback:', err?.message || err);
				webglOK = false;
				renderer = composer = bloomPass = controls = null;
			}
		}

		// Switch the page into the pure-DOM list view. Idempotent — safe to call at
		// startup (no WebGL) or after a runtime context loss. Tears down any live
		// renderer, surfaces the explanatory banner, and lets the legend become the
		// primary, full-height list driven by the same real-time feed.
		let _listFallbackActive = false;
		function enterListFallback(message) {
			webglOK = false;
			if (renderer) {
				try { renderer.forceContextLoss?.(); } catch {}
				try { renderer.dispose(); } catch {}
				try { renderer.domElement.remove(); } catch {}
				renderer = composer = bloomPass = controls = null;
			}
			document.body.classList.add('vz-no-webgl');
			const banner = document.getElementById('vz-fallback');
			if (banner) {
				if (message) {
					const txt = document.getElementById('vz-fallback-text');
					if (txt) txt.innerHTML = `<b>3D view unavailable.</b> ${message}`;
				}
				banner.hidden = false;
			}
			// Make sure the intro overlay can never sit on top of the list.
			try { introEl?.classList.add('is-hidden'); } catch {}
			if (_listFallbackActive) return;
			_listFallbackActive = true;
			// Reveal the controls the WebGL path would unveil on first frame. The
			// intro overlay is hidden above; the feed's first event still calls
			// revealVisualizer() to finish removing it.
			try { controlsEl.hidden = false; } catch {}
			// Re-render whatever data we already have into the list.
			try { applyFilterAndRender(); } catch {}
		}

		// Lights
		scene.add(new THREE.AmbientLight(0xffffff, 0.55));
		const key = new THREE.DirectionalLight(0xc4b5fd, 0.9);
		key.position.set(40, 60, 50);
		scene.add(key);
		const rim = new THREE.DirectionalLight(0x6366f1, 0.45);
		rim.position.set(-50, -20, -40);
		scene.add(rim);

		// Starfield
		(function buildStars() {
			const count = 2500;
			const geom = new THREE.BufferGeometry();
			const positions = new Float32Array(count * 3);
			for (let i = 0; i < count; i++) {
				const r = 180 + Math.random() * 140;
				const t = Math.random() * Math.PI * 2;
				const p = Math.acos(2 * Math.random() - 1);
				positions[i * 3 + 0] = r * Math.sin(p) * Math.cos(t);
				positions[i * 3 + 1] = r * Math.sin(p) * Math.sin(t);
				positions[i * 3 + 2] = r * Math.cos(p);
			}
			geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
			const mat = new THREE.PointsMaterial({ size: 0.6, color: 0xaaaaff, transparent: true, opacity: 0.7, sizeAttenuation: true });
			scene.add(new THREE.Points(geom, mat));
		})();

		// Centerpiece — accent core
		const core = new THREE.Mesh(
			new THREE.IcosahedronGeometry(1.6, 1),
			new THREE.MeshStandardMaterial({ color: 0x8b5cf6, emissive: 0x4c1d95, emissiveIntensity: 0.5, roughness: 0.35, metalness: 0.7, wireframe: false })
		);
		scene.add(core);
		const coreGlow = new THREE.Mesh(
			new THREE.SphereGeometry(2.4, 32, 32),
			new THREE.MeshBasicMaterial({ color: 0x8b5cf6, transparent: true, opacity: 0.12 })
		);
		scene.add(coreGlow);

		// Token meshes
		const tokensGroup = new THREE.Group();
		scene.add(tokensGroup);

		const tokenMeshes = []; // { mesh, ring, data, baseScale, label, sonarRings, deltaPct, flashAt }
		const previousMcaps = new Map(); // mint → last refresh's usd_market_cap, for diff flash
		const textureLoader = new THREE.TextureLoader();
		textureLoader.crossOrigin = 'anonymous';

		// Route remote token art through the same-origin proxy (/api/img) so the
		// browser never makes a cross-origin image request — this eliminates the
		// CORS / ERR_BLOCKED_BY_ORB failures that blanked token textures (one per
		// token in the cloud). data: URIs and already-same-origin paths pass
		// through untouched; the proxy itself falls back to a placeholder on any
		// upstream failure, so a returned src always resolves.
		function proxiedImg(uri, seed) {
			if (!uri || typeof uri !== 'string') return null;
			if (uri.startsWith('data:') || uri.startsWith('/')) return uri;
			const s = seed ? `&seed=${encodeURIComponent(seed)}` : '';
			return `/api/img?url=${encodeURIComponent(uri)}${s}`;
		}

		function fibonacciSphere(n) {
			const points = [];
			const phi = Math.PI * (Math.sqrt(5) - 1);
			for (let i = 0; i < n; i++) {
				const y = 1 - (i / (n - 1)) * 2;
				const r = Math.sqrt(1 - y * y);
				const theta = phi * i;
				points.push({ x: Math.cos(theta) * r, y, z: Math.sin(theta) * r });
			}
			return points;
		}

		// Fallback canvas-textured material when the token image fails to load.
		// Renders the symbol on a tinted background so the sphere is never blank.
		function fallbackTexture(symbol, seedMint) {
			const size = 256;
			const c = document.createElement('canvas');
			c.width = size; c.height = size;
			const ctx = c.getContext('2d');
			const hue = hashStr(seedMint || symbol || 'pump') % 360;
			const grad = ctx.createRadialGradient(size / 2, size / 2, size / 8, size / 2, size / 2, size / 2);
			grad.addColorStop(0, `hsl(${hue}, 70%, 55%)`);
			grad.addColorStop(1, `hsl(${(hue + 40) % 360}, 70%, 25%)`);
			ctx.fillStyle = grad;
			ctx.fillRect(0, 0, size, size);
			ctx.fillStyle = '#fff';
			ctx.font = 'bold 88px "Space Grotesk", system-ui, sans-serif';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			const label = ((symbol || '?').slice(0, 4)).toUpperCase();
			ctx.fillText(label, size / 2, size / 2 + 6);
			const tex = new THREE.CanvasTexture(c);
			tex.colorSpace = THREE.SRGBColorSpace;
			tex.anisotropy = 4;
			return tex;
		}

		function hashStr(s) {
			let h = 0;
			for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0;
			return Math.abs(h);
		}

		// Local, dependency-free avatar for <img> elements (detail panel, legend
		// thumbs). Renders the same tinted symbol badge as fallbackTexture() so
		// avatars never depend on an external service that may be blocked.
		const _avatarCache = new Map();
		function localAvatarDataURL(symbol, seedMint) {
			const key = (seedMint || symbol || 'pump').toLowerCase();
			const cached = _avatarCache.get(key);
			if (cached) return cached;
			const size = 128;
			const c = document.createElement('canvas');
			c.width = size; c.height = size;
			const ctx = c.getContext('2d');
			const hue = hashStr(key) % 360;
			const grad = ctx.createRadialGradient(size / 2, size / 2, size / 8, size / 2, size / 2, size / 2);
			grad.addColorStop(0, `hsl(${hue}, 70%, 55%)`);
			grad.addColorStop(1, `hsl(${(hue + 40) % 360}, 70%, 25%)`);
			ctx.fillStyle = grad;
			ctx.fillRect(0, 0, size, size);
			ctx.fillStyle = '#fff';
			ctx.font = 'bold 48px "Space Grotesk", system-ui, sans-serif';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			const label = ((symbol || '?').slice(0, 4)).toUpperCase();
			ctx.fillText(label, size / 2, size / 2 + 3);
			const url = c.toDataURL('image/png');
			if (_avatarCache.size > 200) _avatarCache.clear();
			_avatarCache.set(key, url);
			return url;
		}

		function loadTokenTexture(url, fallback) {
			return new Promise((resolve) => {
				if (!url) return resolve(fallback);
				textureLoader.load(
					url,
					(tex) => {
						tex.colorSpace = THREE.SRGBColorSpace;
						tex.anisotropy = 4;
						resolve(tex);
					},
					undefined,
					() => resolve(fallback),
				);
			});
		}

		// Sprite label — only built for the top-N spheres so the scene stays clean.
		function buildLabelSprite(symbol, mcap) {
			const w = 384, h = 128;
			const c = document.createElement('canvas');
			c.width = w; c.height = h;
			const ctx = c.getContext('2d');
			ctx.clearRect(0, 0, w, h);
			// Symbol — large, bright
			ctx.font = 'bold 64px "Space Grotesk", system-ui, sans-serif';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			ctx.shadowColor = 'rgba(0, 0, 0, 0.85)';
			ctx.shadowBlur = 8;
			ctx.fillStyle = '#ffffff';
			ctx.fillText('$' + (symbol || '?').toUpperCase().slice(0, 8), w / 2, h / 2 - 18);
			// Mcap — accent green
			ctx.font = '600 38px "JetBrains Mono", ui-monospace, monospace';
			ctx.fillStyle = '#34d399';
			ctx.fillText(mcap, w / 2, h / 2 + 30);
			const tex = new THREE.CanvasTexture(c);
			tex.colorSpace = THREE.SRGBColorSpace;
			tex.anisotropy = 8;
			tex.minFilter = THREE.LinearMipmapLinearFilter;
			tex.needsUpdate = true;
			const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthTest: false, depthWrite: false });
			const sprite = new THREE.Sprite(mat);
			sprite.scale.set(7.5, 2.5, 1);
			sprite.renderOrder = 999;
			return sprite;
		}

		// Live-glow color: green for "just migrated" tokens, red for everything
		// else (fresh mints and pump.fun livestream-active trending tokens).
		function liveGlowHex(token) {
			return token?.is_migration ? 0x34d399 : 0xf87171;
		}

		// Crystalline wireframe cage around higher-cap spheres. Facet count grows
		// with the tier so "shape" reads as a function of market cap. Returned as
		// a child of the sphere so it inherits position + spawn/hover scale; it
		// spins on its own axis in the animation loop.
		function buildTierCage(tier, radius) {
			if (!tier.cage) return null;
			const { detail, scale, color } = tier.cage;
			const base = detail <= 0
				? new THREE.OctahedronGeometry(radius * scale, 0)
				: new THREE.IcosahedronGeometry(radius * scale, Math.min(detail - 1, 2));
			const wire = new THREE.WireframeGeometry(base);
			base.dispose();
			const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.55, depthWrite: false });
			return new THREE.LineSegments(wire, mat);
		}

		function buildTokenMesh(token, position, radius) {
			if (state.renderStyle === 'coin') return buildCoinMesh(token, position, radius);
			const fallback = fallbackTexture(token.symbol, token.mint);
			const isLive = !!token.is_currently_live;
			const glow = liveGlowHex(token);
			const tier = tierForMcap(token.usd_market_cap);
			const material = new THREE.MeshStandardMaterial({
				map: fallback,
				roughness: 0.45,
				metalness: 0.25,
				// Live state owns the glow color (fresh = red, migrated = green);
				// otherwise the market-cap tier tints the emissive.
				emissive: isLive ? new THREE.Color(glow) : new THREE.Color(tier.emissive),
				emissiveIntensity: isLive ? 0.25 : tier.pulse * 0.5,
			});
			const geometry = new THREE.SphereGeometry(radius, 28, 28);
			const mesh = new THREE.Mesh(geometry, material);
			mesh.position.copy(position);
			mesh.scale.setScalar(0.001); // grow in during spawn animation

			const cage = buildTierCage(tier, radius);
			if (cage) mesh.add(cage); // child → follows the sphere's transform

			// Selection / hover ring (hidden by default)
			const ringGeo = new THREE.RingGeometry(radius * 1.18, radius * 1.32, 48);
			const ringMat = new THREE.MeshBasicMaterial({
				color: isLive ? glow : 0x8b5cf6,
				transparent: true,
				opacity: isLive ? 0.45 : 0,
				side: THREE.DoubleSide,
				depthWrite: false,
			});
			const ring = new THREE.Mesh(ringGeo, ringMat);
			ring.position.copy(position);
			ring.lookAt(0, 0, 0);
			ring.scale.setScalar(0.001);

			mesh.userData = { token, ring };

			// Swap to real artwork asynchronously; keeps fallback if it fails.
			if (token.image_uri) {
				loadTokenTexture(proxiedImg(token.image_uri, token.mint || token.symbol), null).then((tex) => {
					if (tex) {
						material.map = tex;
						material.needsUpdate = true;
					}
				});
			}

			return { mesh, ring, isLive, tier, cage, rim: null };
		}

		// Coin-logo render style: each token is a flat, camera-facing medallion so
		// the artwork reads crisply instead of wrapping (and distorting) around a
		// sphere. The logo doubles as the emissive map so the art itself catches the
		// bloom, and a bright tier-/live-colored torus forms the coin's edge. The
		// disc + ring are billboarded toward the camera every frame in animate().
		function buildCoinMesh(token, position, radius) {
			const fallback = fallbackTexture(token.symbol, token.mint);
			const isLive = !!token.is_currently_live;
			const glow = liveGlowHex(token);
			const tier = tierForMcap(token.usd_market_cap);
			const rimColor = isLive ? glow : tier.color;
			const material = new THREE.MeshStandardMaterial({
				map: fallback,
				emissiveMap: fallback,
				emissive: new THREE.Color(0xffffff), // white → logo glows in true colour
				emissiveIntensity: 0.5,
				roughness: 0.5,
				metalness: 0.0,
				side: THREE.DoubleSide,
			});
			const geometry = new THREE.CircleGeometry(radius, 56);
			const mesh = new THREE.Mesh(geometry, material);
			mesh.position.copy(position);
			mesh.quaternion.copy(camera.quaternion); // billboard from the first frame
			mesh.scale.setScalar(0.001);

			// Coin edge — bright unlit torus in the disc's own plane → blooms, and
			// inherits the disc's billboard rotation as a child.
			const rimGeo = new THREE.TorusGeometry(radius * 1.02, Math.max(0.045, radius * 0.07), 14, 56);
			const rimMat = new THREE.MeshBasicMaterial({ color: rimColor, transparent: true, opacity: 0.92 });
			const rim = new THREE.Mesh(rimGeo, rimMat);
			mesh.add(rim);

			// Selection / hover ring — concentric with the coin, billboarded alongside it.
			const ringGeo = new THREE.RingGeometry(radius * 1.2, radius * 1.36, 56);
			const ringMat = new THREE.MeshBasicMaterial({
				color: isLive ? glow : 0x8b5cf6,
				transparent: true,
				opacity: isLive ? 0.45 : 0,
				side: THREE.DoubleSide,
				depthWrite: false,
			});
			const ring = new THREE.Mesh(ringGeo, ringMat);
			ring.position.copy(position);
			ring.quaternion.copy(camera.quaternion);
			ring.scale.setScalar(0.001);

			mesh.userData = { token, ring };

			if (token.image_uri) {
				loadTokenTexture(proxiedImg(token.image_uri, token.mint || token.symbol), null).then((tex) => {
					if (tex) {
						material.map = tex;
						material.emissiveMap = tex;
						material.needsUpdate = true;
					}
				});
			}

			return { mesh, ring, isLive, tier, cage: null, rim };
		}

		function placeTokens(tokens) {
			if (!webglOK) return; // list-view fallback renders from state.all via the legend
			// Snapshot previous mcaps so the new entries can compute a delta.
			tokenMeshes.forEach((entry) => {
				const m = Number(entry.data?.usd_market_cap) || 0;
				if (entry.data?.mint && m > 0) previousMcaps.set(entry.data.mint, m);
			});
			// Wipe previous run so refresh swaps cleanly.
			while (tokensGroup.children.length) {
				const child = tokensGroup.children[0];
				tokensGroup.remove(child);
				// Traverse so a sphere's tier-cage child is disposed alongside it.
				// Sprites share a single geometry across instances — don't dispose it.
				child.traverse((node) => {
					if (node.geometry && !node.isSprite) node.geometry.dispose();
					if (node.material) {
						if (node.material.map) node.material.map.dispose();
						node.material.dispose();
					}
				});
			}
			tokenMeshes.length = 0;

			const caps = tokens.map((t) => Math.max(1, Number(t.usd_market_cap) || 0));
			const maxLog = Math.log10(Math.max(...caps, 10));
			const minLog = Math.log10(Math.max(Math.min(...caps), 1));
			const span = Math.max(0.0001, maxLog - minLog);

			const points = fibonacciSphere(tokens.length);
			const spawnStart = performance.now();

			tokens.forEach((token, i) => {
				const cap = caps[i];
				const t = (Math.log10(cap) - minLog) / span;
				const radius = MIN_TOKEN_R + t * (MAX_TOKEN_R - MIN_TOKEN_R);

				// Wobble each point inward a touch for big caps so they don't all sit on a perfect shell.
				const shellR = SPHERE_RADIUS * (0.82 + (1 - t) * 0.25);
				const p = points[i];
				const position = new THREE.Vector3(p.x * shellR, p.y * shellR, p.z * shellR);

				const { mesh, ring, isLive, tier, cage, rim } = buildTokenMesh(token, position, radius);
				tokensGroup.add(mesh);
				tokensGroup.add(ring);
				const prevMcap = previousMcaps.get(token.mint);
				const currMcap = Number(token.usd_market_cap) || 0;
				let deltaPct = 0;
				if (prevMcap && prevMcap > 0 && currMcap > 0) {
					deltaPct = (currMcap - prevMcap) / prevMcap;
				}
				const entry = {
					mesh, ring, data: token,
					baseScale: 1,
					radius,
					isLive,
					tier, cage, rim,
					style: state.renderStyle,
					spawnAt: spawnStart + i * 22, // ms — stagger reveals
					spawned: false,
					hoverScale: 1,
					surge: 1,
					visible: true,
					label: null,            // sprite, attached lazily for top-N
					labelOffset: radius + 1.6,
					sonarRings: [],         // expanding "broadcasting" rings for live tokens
					nextSonarAt: 0,
					deltaPct,               // refresh-to-refresh change
					// The diff-flash recolours the mesh emissive — only meaningful for
					// orbs. Coins convey movement via the persistent up/down colour wash
					// and surge, keeping the logo glowing in true colour.
					flashAt: (state.renderStyle === 'orb' && deltaPct !== 0) ? performance.now() + 50 + i * 30 : 0,
				};
				tokenMeshes.push(entry);
				if (isLive) seedSonarRing(entry);
			});
		}

		// ── live "broadcasting" rings — sonar pings out of live spheres ──
		function seedSonarRing(entry) {
			const ringGeo = new THREE.RingGeometry(entry.radius * 1.05, entry.radius * 1.18, 48);
			const ringMat = new THREE.MeshBasicMaterial({
				color: liveGlowHex(entry.data),
				transparent: true,
				opacity: 0.7,
				side: THREE.DoubleSide,
				depthWrite: false,
			});
			const ring = new THREE.Mesh(ringGeo, ringMat);
			ring.position.copy(entry.mesh.position);
			ring.lookAt(0, 0, 0);
			ring.userData = { bornAt: performance.now(), life: 1600, baseR: entry.radius };
			tokensGroup.add(ring);
			entry.sonarRings.push(ring);
		}

		// ── always-on labels for top-N (recomputed on filter/sort) ──
		function syncLabels() {
			// Find the top-N visible entries by current sort.
			const visible = tokenMeshes
				.filter((e) => e.visible)
				.slice(0, LABEL_COUNT);
			const winners = new Set(visible);
			tokenMeshes.forEach((entry) => {
				const wants = winners.has(entry);
				if (wants && !entry.label) {
					entry.label = buildLabelSprite(entry.data.symbol, formatMcap(entry.data.usd_market_cap));
					tokensGroup.add(entry.label);
				} else if (!wants && entry.label) {
					tokensGroup.remove(entry.label);
					if (entry.label.material.map) entry.label.material.map.dispose();
					entry.label.material.dispose();
					entry.label = null;
				}
			});
		}

		function applyVisibility(filteredMints) {
			const set = filteredMints ? new Set(filteredMints) : null;
			tokenMeshes.forEach((entry) => {
				const show = !set || set.has(entry.data.mint);
				entry.visible = show;
				entry.mesh.visible = show;
				// Ring stays hidden when filtered out, regardless of live state.
				if (!show) entry.ring.visible = false;
				else entry.ring.visible = true;
				// Sonar rings only meaningful for visible live tokens.
				entry.sonarRings.forEach((sr) => { sr.visible = show; });
				if (entry.label) entry.label.visible = show;
			});
			// Reorder tokenMeshes to match the filtered/sorted rank so syncLabels
			// can pluck the top-N straight off the front of the array.
			if (filteredMints) {
				const rank = new Map(filteredMints.map((m, i) => [m, i]));
				tokenMeshes.sort((a, b) => {
					const ra = rank.has(a.data.mint) ? rank.get(a.data.mint) : Number.POSITIVE_INFINITY;
					const rb = rank.has(b.data.mint) ? rank.get(b.data.mint) : Number.POSITIVE_INFINITY;
					return ra - rb;
				});
			}
			syncLabels();
		}

		// ── interactivity ────────────────────────────────────────────
		const raycaster = new THREE.Raycaster();
		const pointer = new THREE.Vector2();
		let hovered = null;
		let selected = null;

		// Pointer interaction is only meaningful when there's a 3D canvas. Without
		// WebGL the list-view fallback drives navigation via legend clicks instead.
		let pressStart = null;
		if (renderer) {
			renderer.domElement.addEventListener('pointermove', (ev) => {
				const rect = renderer.domElement.getBoundingClientRect();
				pointer.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1;
				pointer.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
				tooltip.style.left = ev.clientX + 'px';
				tooltip.style.top = ev.clientY + 'px';
			});

			// Click vs drag detection — OrbitControls swallows drags but we still
			// want to suppress clicks that came from a long mouse-down or movement.
			renderer.domElement.addEventListener('pointerdown', (ev) => {
				pressStart = { x: ev.clientX, y: ev.clientY, t: Date.now() };
			});
			renderer.domElement.addEventListener('pointerup', (ev) => {
				if (!pressStart) return;
				const dx = ev.clientX - pressStart.x;
				const dy = ev.clientY - pressStart.y;
				const dt = Date.now() - pressStart.t;
				pressStart = null;
				if (Math.hypot(dx, dy) > 6 || dt > 350) return;
				handleClick();
			});
		}

		function visibleMeshes() {
			return tokenMeshes.filter((t) => t.visible).map((t) => t.mesh);
		}

		function handleClick() {
			raycaster.setFromCamera(pointer, camera);
			const hits = raycaster.intersectObjects(visibleMeshes(), false);
			if (!hits.length) return;
			const data = hits[0].object.userData.token;
			selectToken(data);
		}

		// A pump.fun mint is a base58 string (no 0/O/I/l). Guard navigation so a
		// missing/empty/malformed mint never produces a broken /coin3d?mint= URL.
		function isValidMint(mint) {
			return typeof mint === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(mint.trim());
		}
		function openCoin3d(mint) {
			if (!isValidMint(mint)) return false;
			window.location.href = `/coin3d?mint=${encodeURIComponent(mint.trim())}`;
			return true;
		}

		// Double-click drills straight into the full 3D coin page (same tab).
		if (renderer) {
			renderer.domElement.addEventListener('dblclick', () => {
				raycaster.setFromCamera(pointer, camera);
				const hits = raycaster.intersectObjects(visibleMeshes(), false);
				if (!hits.length) return;
				openCoin3d(hits[0].object.userData.token?.mint);
			});
		}

		function setHovered(entry) {
			if (hovered === entry) return;
			if (hovered && hovered !== selected) {
				// Restore non-selected previous hover ring.
				hovered.ring.material.opacity = hovered.isLive ? 0.45 : 0;
			}
			hovered = entry;
			if (entry) {
				if (entry !== selected) entry.ring.material.opacity = 0.7;
				host.classList.add('is-pointing');
				ttName.textContent = (entry.data.name || 'Unknown') + (entry.data.symbol ? ` · $${entry.data.symbol}` : '');
				ttMcap.textContent = formatMcap(entry.data.usd_market_cap);
				tooltip.classList.add('is-visible');
			} else {
				host.classList.remove('is-pointing');
				tooltip.classList.remove('is-visible');
			}
		}

		function selectToken(token) {
			const entry = tokenMeshes.find((t) => t.data.mint === token.mint);
			// In the list-view fallback there are no meshes — still open the detail
			// panel and highlight the legend row so selection works without WebGL.
			if (entry) {
				if (selected && selected !== entry) {
					selected.ring.material.opacity = selected.isLive ? 0.45 : 0;
					selected.ring.material.color.set(selected.isLive ? liveGlowHex(selected.data) : 0x8b5cf6);
				}
				selected = entry;
				selected.ring.material.color.set(0x34d399);
				selected.ring.material.opacity = 1;
			} else if (!webglOK) {
				selected = null;
			} else {
				return;
			}
			if (controls) controls.autoRotate = false;
			renderDetail(token);
			highlightLegend(token.mint);
		}

		function clearSelection() {
			if (selected) {
				selected.ring.material.opacity = selected.isLive ? 0.45 : 0;
				selected.ring.material.color.set(selected.isLive ? liveGlowHex(selected.data) : 0x8b5cf6);
				selected = null;
			}
			detailEl.classList.remove('is-open');
			detailEl.setAttribute('aria-hidden', 'true');
			if (controls) controls.autoRotate = true;
			highlightLegend(null);
		}

		detailClose.addEventListener('click', clearSelection);
		document.addEventListener('keydown', (ev) => {
			if (ev.key === 'Escape') {
				if (document.activeElement === searchInput) {
					searchInput.value = '';
					applyFilterAndRender();
					searchInput.blur();
				} else {
					clearSelection();
				}
			} else if (ev.key === '/' && document.activeElement !== searchInput) {
				ev.preventDefault();
				searchInput.focus();
				searchInput.select();
			} else if (ev.key.toLowerCase() === 'r' && document.activeElement !== searchInput && !ev.metaKey && !ev.ctrlKey) {
				if (!refreshBtn.disabled) {
					clearSelection();
					loadData();
				}
			} else if (ev.key.toLowerCase() === 'c' && document.activeElement !== searchInput && !ev.metaKey && !ev.ctrlKey) {
				// Toggle the render style (Coins ⟷ Orbs).
				setRenderStyle(state.renderStyle === 'coin' ? 'orb' : 'coin');
			}
		});

		// ── extra real-data rows: creator track record, distance from ATH,
		//    migration liquidity. Every value traces to data already on the token —
		//    no extra fetch, no placeholders. Rows render only when their data exists.
		function shortAddr(a) {
			const s = String(a || '');
			return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;
		}
		function metaRow(key, valueNode) {
			const row = document.createElement('div');
			row.className = 'meta-row';
			const k = document.createElement('span');
			k.className = 'k';
			k.textContent = key;
			row.appendChild(k);
			if (typeof valueNode === 'string') {
				const v = document.createElement('span');
				v.className = 'v';
				v.innerHTML = valueNode;
				row.appendChild(v);
			} else {
				valueNode.classList.add('v');
				row.appendChild(valueNode);
			}
			return row;
		}
		function renderDetailExtra(token) {
			const host = document.getElementById('vz-detail-extra');
			if (!host) return;
			host.innerHTML = '';

			// Creator track record — launches and how many of them graduated. A high
			// graduation rate is a real credibility signal; a serial-launcher with
			// zero graduations is a real warning. Both numbers are on the token.
			const launches = Number(token.creator_launches);
			if (token.creator && Number.isFinite(launches) && launches > 0) {
				const graduated = Number(token.creator_graduated) || 0;
				const rate = Math.round((graduated / launches) * 100);
				const rateClass = rate >= 30 ? 'good' : rate === 0 ? 'bad' : 'dim';
				const val = `${launches.toLocaleString()} launch${launches === 1 ? '' : 'es'} · `
					+ `<span class="${rateClass}">${graduated.toLocaleString()} graduated (${rate}%)</span>`;
				if (isValidMint(token.creator)) {
					const a = document.createElement('a');
					a.href = `https://solscan.io/account/${token.creator}`;
					a.target = '_blank';
					a.rel = 'noopener noreferrer';
					a.innerHTML = `${val} <span class="dim">· ${shortAddr(token.creator)} ↗</span>`;
					host.appendChild(metaRow('Creator', a));
				} else {
					host.appendChild(metaRow('Creator', val));
				}
			}

			// Distance from all-time-high market cap — how far the coin has retraced.
			const mc = Number(token.usd_market_cap) || 0;
			const ath = Number(token.ath_market_cap) || 0;
			if (mc > 0 && ath > mc * 1.01) {
				const downPct = Math.round(((ath - mc) / ath) * 100);
				host.appendChild(metaRow('From ATH', `<span class="bad">−${downPct}%</span> <span class="dim">· ATH ${formatMcap(ath)}</span>`));
			} else if (mc > 0 && ath > 0 && mc >= ath * 0.99) {
				host.appendChild(metaRow('From ATH', `<span class="good">at the high</span>`));
			}

			// Migration liquidity — for graduated coins, how much SOL/USD seeded the pool.
			if (token.is_migration) {
				const usd = Number(token.amount_usd) || 0;
				const sol = Number(token.amount_sol) || 0;
				if (usd > 0 || sol > 0) {
					const parts = [];
					if (usd > 0) parts.push(formatMcap(usd));
					if (sol > 0) parts.push(`${sol.toLocaleString(undefined, { maximumFractionDigits: 2 })} SOL`);
					host.appendChild(metaRow('Graduated with', `<span class="good">${parts.join(' · ')}</span>`));
				}
			}
		}

		// ── detail panel rendering ───────────────────────────────────
		function renderDetail(token) {
			const avatar = document.getElementById('vz-detail-avatar');
			const fallbackAvatar = localAvatarDataURL(token.symbol, token.mint || token.symbol);
			avatar.src = proxiedImg(token.image_uri, token.mint || token.symbol) || fallbackAvatar;
			avatar.onerror = () => { avatar.onerror = null; avatar.src = fallbackAvatar; };

			document.getElementById('vz-detail-name').textContent = token.name || 'Unknown';
			document.getElementById('vz-detail-symbol').textContent = token.symbol ? '$' + token.symbol : '';

			document.getElementById('vz-detail-mcap').textContent = formatMcap(token.usd_market_cap);
			document.getElementById('vz-detail-ath').textContent = formatMcap(token.ath_market_cap);
			document.getElementById('vz-detail-replies').textContent = token.reply_count != null ? Number(token.reply_count).toLocaleString() : NO_VALUE;
			document.getElementById('vz-detail-age').textContent = formatAge(token.created_timestamp);

			renderDetailExtra(token);

			const desc = (token.description || '').trim();
			const descEl = document.getElementById('vz-detail-description');
			descEl.textContent = desc.length > 800 ? desc.slice(0, 800) + '…' : desc;

			document.getElementById('vz-detail-mint').textContent = token.mint || '';
			const liveBadge = document.getElementById('vz-detail-live');
			liveBadge.hidden = !token.is_currently_live;
			if (token.is_migration) {
				liveBadge.classList.add('is-grad');
				liveBadge.textContent = 'Just migrated';
			} else {
				liveBadge.classList.remove('is-grad');
				liveBadge.textContent = 'Live now';
			}

			const linksEl = document.getElementById('vz-detail-links');
			linksEl.innerHTML = '';
			if (token.mint) {
				// Primary action is the real on-chain buy — ape the coin without ever
				// leaving the visualizer. The trade modal (src/game/coin-buy.js) builds
				// the unsigned tx server-side, the connected Solana wallet signs it, and
				// it settles through the same-origin RPC proxy. Lazy-loaded on click so
				// the heavy Solana/pump SDKs never weigh down the visualizer bundle.
				linksEl.appendChild(buyButtonNode(token));
				if (isValidMint(token.mint)) {
					linksEl.appendChild(linkNode(`/coin3d?mint=${encodeURIComponent(token.mint.trim())}`, 'Open in 3D →', { internal: true }));
				}
				linksEl.appendChild(linkNode(`https://pump.fun/coin/${token.mint}`, 'Pump.fun ↗'));
				linksEl.appendChild(linkNode(`https://solscan.io/token/${token.mint}`, 'Solscan ↗'));
			}
			if (token.twitter) linksEl.appendChild(linkNode(token.twitter, 'Twitter ↗'));
			if (token.telegram) linksEl.appendChild(linkNode(token.telegram, 'Telegram ↗'));
			if (token.website) linksEl.appendChild(linkNode(token.website, 'Website ↗'));

			// Watchlist button
			if (token.mint) {
				const wBtn = document.createElement('button');
				wBtn.type = 'button';
				const watched = isWatchedVz(token.mint);
				wBtn.textContent = watched ? '★ Watching' : '☆ Watch';
				wBtn.setAttribute('aria-pressed', String(watched));
				wBtn.setAttribute('aria-label', watched ? 'Remove from watchlist' : 'Add to watchlist');
				wBtn.dataset.watchMint = token.mint;
				wBtn.addEventListener('click', () => {
					const now = toggleVzWatch(token.mint);
					wBtn.textContent = now ? '★ Watching' : '☆ Watch';
					wBtn.setAttribute('aria-pressed', String(now));
					wBtn.setAttribute('aria-label', now ? 'Remove from watchlist' : 'Add to watchlist');
				});
				linksEl.appendChild(wBtn);
				linksEl.appendChild(linkNode(`/oracle/coin/${encodeURIComponent(token.mint)}`, 'Oracle →', { internal: true }));
			}

			detailEl.classList.add('is-open');
			detailEl.setAttribute('aria-hidden', 'false');

			// Async: fetch Oracle conviction for this coin
			const oracleSlot = document.getElementById('vz-oracle-slot');
			if (token.mint && oracleSlot) {
				oracleSlot.innerHTML = '<div class="vz-oracle-sk"></div>';
				fetchOracleConviction(token.mint).then((cv) => {
					if (!cv) { oracleSlot.innerHTML = ''; return; }
					const TIER_COLOR = { prime: '#c084fc', strong: '#34d399', lean: '#fbbf24', watch: '#94a3b8', avoid: '#f87171' };
					const color = TIER_COLOR[cv.tier] || '#94a3b8';
					oracleSlot.innerHTML = `<a class="vz-oracle" href="/oracle/coin/${encodeURIComponent(token.mint)}" aria-label="Oracle conviction: ${cv.score} — ${cv.tier}">
						<div>
							<div class="vz-oracle-label">Oracle conviction</div>
							<div class="vz-oracle-score" style="color:${color}">${cv.score}</div>
						</div>
						<div class="vz-oracle-tier" style="color:${color}">${cv.tier || ''}</div>
					</a>`;
				}).catch(() => { oracleSlot.innerHTML = ''; });
			} else if (oracleSlot) {
				oracleSlot.innerHTML = '';
			}
		}

		// Bounded conviction cache — entries expire after ORACLE_TTL_MS (so a coin's
		// conviction can refresh over a long session) and the Map is capped at
		// ORACLE_CACHE_MAX (oldest evicted first) so it never creeps unbounded.
		const ORACLE_TTL_MS = 5 * 60 * 1000;
		const ORACLE_CACHE_MAX = 500;
		const _oracleCache = new Map(); // mint → { value, expires }
		async function fetchOracleConviction(mint) {
			const now = Date.now();
			const hit = _oracleCache.get(mint);
			if (hit && hit.expires > now) {
				// Refresh LRU position so frequently-viewed coins survive eviction.
				_oracleCache.delete(mint);
				_oracleCache.set(mint, hit);
				return hit.value;
			}
			if (hit) _oracleCache.delete(mint);
			try {
				const r = await fetch(`/api/oracle/coin?mint=${encodeURIComponent(mint)}&network=mainnet`);
				if (!r.ok) {
					// 404 = mint not observed yet — a stable negative. Cache it under the
					// same TTL so a repaint-driven re-render doesn't re-fetch (and re-404)
					// every frame. A 503 is transient: return null without caching so the
					// next call retries.
					if (r.status === 404) _oracleCache.set(mint, { value: null, expires: now + ORACLE_TTL_MS });
					return null;
				}
				const d = await r.json();
				const cv = d?.conviction ? { score: d.conviction.score, tier: d.conviction.tier } : null;
				_oracleCache.set(mint, { value: cv, expires: now + ORACLE_TTL_MS });
				if (_oracleCache.size > ORACLE_CACHE_MAX) {
					const oldest = _oracleCache.keys().next().value;
					if (oldest !== undefined) _oracleCache.delete(oldest);
				}
				return cv;
			} catch { return null; }
		}

		const VZ_WATCH_KEY = 'ld_watchlist';
		function isWatchedVz(mint) {
			try { const a = JSON.parse(localStorage.getItem(VZ_WATCH_KEY) || '[]'); return Array.isArray(a) && a.includes(mint); }
			catch { return false; }
		}
		function toggleVzWatch(mint) {
			try {
				const a = JSON.parse(localStorage.getItem(VZ_WATCH_KEY) || '[]');
				const list = Array.isArray(a) ? a : [];
				const idx = list.indexOf(mint);
				if (idx >= 0) list.splice(idx, 1); else list.unshift(mint);
				localStorage.setItem(VZ_WATCH_KEY, JSON.stringify(list.slice(0, 200)));
				return idx < 0;
			} catch { return false; }
		}

		function linkNode(href, label, opts = {}) {
			const { primary = false, internal = false } = opts;
			const a = document.createElement('a');
			a.href = href;
			if (!internal) {
				a.target = '_blank';
				a.rel = 'noopener noreferrer';
			}
			a.textContent = label;
			if (primary) a.className = 'primary';
			return a;
		}

		// Primary "Buy" CTA for the detail panel. Opens the native on-chain trade
		// modal for the selected coin — a real bonding-curve / AMM buy through the
		// connected Solana wallet, not a redirect off-site. The heavy Solana + pump
		// SDKs that power the modal are pulled in only on the first click.
		let _tradeModuleP = null;
		function buyButtonNode(token) {
			const sym = token.symbol ? '$' + String(token.symbol).toUpperCase() : '';
			const btn = document.createElement('button');
			btn.type = 'button';
			btn.className = 'primary';
			btn.textContent = sym ? `Buy ${sym}` : 'Buy coin';
			btn.setAttribute('aria-label', sym ? `Buy ${sym}` : 'Buy this coin');
			btn.addEventListener('click', () => openTradeForToken(token, btn));
			return btn;
		}

		async function openTradeForToken(token, btn) {
			if (!token?.mint) return;
			const restore = btn ? btn.textContent : null;
			if (btn) { btn.disabled = true; btn.textContent = 'Loading…'; }
			try {
				if (!_tradeModuleP) _tradeModuleP = import('/src/game/coin-buy.js');
				const { openBuyModal } = await _tradeModuleP;
				openBuyModal({
					mint: token.mint,
					name: token.name || token.symbol || 'coin',
					symbol: token.symbol || '',
					image: proxiedImg(token.image_uri, token.mint || token.symbol) || '',
				});
			} catch (err) {
				// Never strand the user on a dead button — surface the failure and let
				// them retry, or fall back to the full coin page where they can also buy.
				_tradeModuleP = null;
				console.error('[pump-visualizer] trade modal failed to load', err);
				if (btn) {
					btn.textContent = 'Retry buy';
					btn.disabled = false;
				}
				return;
			}
			if (btn) { btn.disabled = false; btn.textContent = restore; }
		}

		// ── formatters ───────────────────────────────────────────────
		function formatMcap(v) {
			const n = Number(v);
			if (!Number.isFinite(n) || n <= 0) return NO_VALUE;
			if (n >= 1e9) return '$' + (n / 1e9).toFixed(2) + 'B';
			if (n >= 1e6) return '$' + (n / 1e6).toFixed(2) + 'M';
			if (n >= 1e3) return '$' + (n / 1e3).toFixed(1) + 'K';
			return '$' + n.toFixed(2);
		}
		function formatAge(ts) {
			const n = Number(ts);
			if (!Number.isFinite(n) || n <= 0) return NO_VALUE;
			const ms = Date.now() - n;
			const days = ms / 86_400_000;
			if (days >= 30) return Math.floor(days / 30) + 'mo';
			if (days >= 1) return Math.floor(days) + 'd';
			const hours = ms / 3_600_000;
			if (hours >= 1) return Math.floor(hours) + 'h';
			return Math.max(1, Math.floor(ms / 60_000)) + 'm';
		}

		// ── legend ───────────────────────────────────────────────────
		function renderLegend(tokens) {
			legendList.innerHTML = '';
			legendEl.classList.toggle('is-empty', tokens.length === 0);
			const isFeed = state.mode === 'feed' || state.mode === 'migrations';
			// The 3D overlay legend stays compact (top 20); the list-view fallback is
			// the primary surface and renders everything it's handed.
			const cap = webglOK ? 20 : tokens.length;
			tokens.slice(0, cap).forEach((token, i) => {
				const li = document.createElement('li');
				li.dataset.mint = token.mint || '';
				if (token.is_currently_live) li.classList.add('is-live');

				const rank = document.createElement('span');
				rank.className = 'rank';
				if (isFeed) {
					rank.classList.add('age');
					rank.dataset.ts = String(token.created_timestamp || 0);
					rank.textContent = formatAgeShort(token.created_timestamp);
				} else {
					rank.textContent = '#' + (i + 1);
				}

				const thumb = document.createElement('img');
				thumb.className = 'thumb';
				thumb.alt = '';
				thumb.loading = 'lazy';
				thumb.referrerPolicy = 'no-referrer';
				const thumbFallback = localAvatarDataURL(token.symbol, token.mint || token.symbol);
				thumb.src = proxiedImg(token.image_uri, token.mint || token.symbol) || thumbFallback;
				thumb.onerror = () => { thumb.onerror = null; thumb.src = thumbFallback; };

				const name = document.createElement('span');
				name.className = 'name';
				name.textContent = token.name || 'Unknown';

				const sym = document.createElement('span');
				sym.className = 'sym';
				sym.textContent = token.symbol ? '$' + token.symbol : '';

				const mc = document.createElement('span');
				mc.className = 'mc';
				mc.textContent = formatMcap(token.usd_market_cap);

				li.appendChild(rank);
				li.appendChild(thumb);
				li.appendChild(name);
				li.appendChild(sym);
				li.appendChild(mc);

				if (token.is_currently_live) {
					const eq = document.createElement('span');
					eq.className = 'vz-eq';
					eq.setAttribute('aria-hidden', 'true');
					eq.innerHTML = '<span></span><span></span><span></span><span></span>';
					const pill = document.createElement('span');
					pill.className = 'vz-live-pill';
					pill.textContent = state.mode === 'migrations' ? 'Grad' : (isFeed ? 'New' : 'Live');
					li.appendChild(eq);
					li.appendChild(pill);
				}

				li.tabIndex = 0;
				li.setAttribute('role', 'button');
				li.setAttribute('aria-label', 'View details for ' + (token.name || 'Unknown') + (token.symbol ? ' ($' + token.symbol + ')' : ''));
				li.addEventListener('click', () => focusToken(token));
				li.addEventListener('keydown', (e) => {
					if (e.key === 'Enter' || e.key === ' ') {
						e.preventDefault();
						focusToken(token);
					}
				});
				legendList.appendChild(li);
			});
			legendEl.hidden = false;
		}

		function formatAgeShort(ts) {
			const n = Number(ts);
			if (!Number.isFinite(n) || n <= 0) return 'now';
			const ms = Date.now() - n;
			if (ms < 5_000) return 'now';
			if (ms < 60_000) return Math.floor(ms / 1000) + 's';
			if (ms < 3_600_000) return Math.floor(ms / 60_000) + 'm';
			if (ms < 86_400_000) return Math.floor(ms / 3_600_000) + 'h';
			return Math.floor(ms / 86_400_000) + 'd';
		}

		// Refresh the "5s / 2m / …" age cells in the legend so they tick up live.
		setInterval(() => {
			if (state.mode !== 'feed') return;
			legendList.querySelectorAll('.rank.age').forEach((el) => {
				const ts = Number(el.dataset.ts);
				if (ts) el.textContent = formatAgeShort(ts);
			});
		}, 1000);
		function highlightLegend(mint) {
			legendList.querySelectorAll('li').forEach((li) => {
				li.classList.toggle('is-selected', !!mint && li.dataset.mint === mint);
			});
		}

		// Camera tween — used both for the intro fly-in and clicked-token focus.
		const tween = { active: false, from: new THREE.Vector3(), to: new THREE.Vector3(), target: new THREE.Vector3(), start: 0, duration: 700, targetLerp: 0.4 };
		function focusToken(token) {
			selectToken(token);
			const entry = tokenMeshes.find((t) => t.data.mint === token.mint);
			if (!entry) return;
			const pos = entry.mesh.position.clone();
			const dir = pos.clone().normalize();
			const dest = pos.clone().add(dir.multiplyScalar(8));
			tween.from.copy(camera.position);
			tween.to.copy(dest);
			tween.target.copy(pos);
			tween.start = performance.now();
			tween.duration = 700;
			tween.targetLerp = 0.4;
			tween.active = true;
		}
		function startIntroFlyIn() {
			tween.from.copy(camera.position);
			tween.to.set(0, 8, 70);
			tween.target.set(0, 0, 0);
			tween.start = performance.now();
			tween.duration = 1800;
			tween.targetLerp = 1.0;
			tween.active = true;
		}
		function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
		function easeOutBack(t) {
			const c = 1.70158;
			return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2);
		}

		// ── animation loop ───────────────────────────────────────────
		let frameCount = 0;
		function animate() {
			requestAnimationFrame(animate);
			const time = performance.now();
			frameCount++;

			core.rotation.x += 0.003;
			core.rotation.y += 0.005;
			coreGlow.scale.setScalar(1 + Math.sin(time * 0.0015) * 0.04);

			if (tween.active) {
				const t = Math.min(1, (time - tween.start) / tween.duration);
				const e = easeOutCubic(t);
				camera.position.lerpVectors(tween.from, tween.to, e);
				controls.target.lerp(tween.target, e * tween.targetLerp);
				if (t >= 1) tween.active = false;
			}

			// Per-token: spawn animation, hover scale lerp, live pulse, flash, sonar.
			const evictedThisFrame = [];
			tokenMeshes.forEach((entry) => {
				// Coin style: billboard the disc (and its selection ring) toward the
				// camera every frame so the logo always faces the viewer head-on. Done
				// before the fade/spawn early-returns so spawning coins never flash edge-on.
				if (entry.style === 'coin') {
					entry.mesh.quaternion.copy(camera.quaternion);
					entry.ring.quaternion.copy(camera.quaternion);
				}
				// Fade-out (feed eviction): shrink + drop opacity then remove.
				if (entry.fadeOutAt) {
					const t = Math.min(1, (time - entry.fadeOutAt) / FEED_FADE_OUT_MS);
					const k = 1 - t;
					entry.mesh.scale.setScalar(Math.max(0.001, k));
					entry.ring.scale.setScalar(Math.max(0.001, k));
					if (entry.mesh.material) {
						entry.mesh.material.transparent = true;
						entry.mesh.material.opacity = k;
					}
					if (entry.ring.material) entry.ring.material.opacity *= k;
					if (t >= 1) evictedThisFrame.push(entry);
					return;
				}
				if (!entry.visible) return;
				// Spawn pop-in (stagger).
				if (!entry.spawned) {
					const dt = time - entry.spawnAt;
					if (dt > 0) {
						const t = Math.min(1, dt / 600);
						const e = easeOutBack(t);
						entry.mesh.scale.setScalar(e);
						entry.ring.scale.setScalar(e);
						if (t >= 1) entry.spawned = true;
					}
					return;
				}
				// Hover scale ease.
				const wantHover = (entry === hovered || entry === selected) ? 1.18 : 1;
				entry.hoverScale += (wantHover - entry.hoverScale) * 0.18;

				// Market-cap tier motion — self-rotation plus an independently
				// spinning cage, energy scaling with the tier. Bigger cap = livelier.
				// Coins stay billboarded (handled above), so spin only applies to orbs.
				if (entry.tier && entry.style !== 'coin') {
					entry.mesh.rotation.y += entry.tier.spin * 0.01;
					if (entry.cage) {
						entry.cage.rotation.y -= entry.tier.spin * 0.014;
						entry.cage.rotation.x += entry.tier.spin * 0.006;
					}
				}

				// Move surge: the diff-flash pops this >1 when the cap rose between
				// refreshes, <1 when it fell; here it eases back to rest each frame.
				entry.surge += (1 - entry.surge) * 0.12;
				entry.mesh.scale.setScalar(entry.hoverScale * entry.surge);

				// Persistent tint by refresh-to-refresh delta — subtle wash on top of texture.
				if (entry.deltaPct !== 0 && entry.mesh.material) {
					const mag = Math.min(1, Math.abs(entry.deltaPct) * 4); // ±25% saturates
					if (entry.deltaPct > 0) {
						entry.mesh.material.color.setRGB(1 - mag * 0.45, 1, 1 - mag * 0.45);
					} else {
						entry.mesh.material.color.setRGB(1, 1 - mag * 0.55, 1 - mag * 0.55);
					}
				}

				// Diff-flash: a refresh moved this coin's cap. Burst emissive green
				// (up) or red (down), pop/dip the scale, and flare the cage — the
				// "as it goes up / down" signal layered over the steady tier look.
				if (entry.flashAt && time >= entry.flashAt) {
					const fdt = time - entry.flashAt;
					if (fdt < FLASH_DURATION_MS) {
						const k = 1 - (fdt / FLASH_DURATION_MS);
						const burst = k * k * 1.4;
						const positive = entry.deltaPct > 0;
						const flashColor = positive ? new THREE.Color(0x34d399) : new THREE.Color(0xf87171);
						entry.mesh.material.emissive.copy(flashColor);
						entry.mesh.material.emissiveIntensity = burst;
						entry.surge = 1 + (positive ? 1 : -1) * 0.14 * k;
						if (entry.cage) entry.cage.material.opacity = Math.min(1, 0.55 + burst * 0.4);
					} else {
						entry.flashAt = 0;
						entry.mesh.material.emissive.copy(entry.isLive ? new THREE.Color(liveGlowHex(entry.data)) : new THREE.Color(entry.tier ? entry.tier.emissive : 0x000000));
						entry.mesh.material.emissiveIntensity = entry.isLive ? 0.25 : (entry.tier ? entry.tier.pulse : 0);
						if (entry.cage) entry.cage.material.opacity = 0.55;
					}
				}

				// Live pulse on emissive + ring. Coins keep a higher emissive floor so
				// the logo (which is the emissive map) stays brightly legible.
				const isCoin = entry.style === 'coin';
				if (entry.isLive && !entry.flashAt) {
					const pulse = 0.5 + 0.5 * Math.sin(time * 0.006 + entry.spawnAt * 0.001);
					entry.mesh.material.emissiveIntensity = (isCoin ? 0.5 : 0.18) + pulse * 0.35;
					if (entry !== selected && entry !== hovered) {
						entry.ring.material.opacity = 0.35 + pulse * 0.35;
					}
					entry.ring.scale.setScalar(entry.hoverScale * (1 + pulse * 0.06));
				} else {
					// Non-live: breathe the emissive at the tier's own pace + intensity.
					if (!entry.flashAt && entry.tier) {
						const tp = 0.5 + 0.5 * Math.sin(time * entry.tier.pulseRate + entry.spawnAt * 0.0011);
						const base = isCoin ? 0.55 : entry.tier.pulse;
						entry.mesh.material.emissiveIntensity = base * (0.55 + tp * 0.9);
					}
					if (entry !== selected) entry.ring.scale.setScalar(entry.hoverScale);
				}

				// Sonar rings — emit a new one every ~1.4s while live; expand & fade existing.
				if (entry.isLive) {
					if (time >= entry.nextSonarAt) {
						seedSonarRing(entry);
						entry.nextSonarAt = time + 1400;
					}
				}
				for (let i = entry.sonarRings.length - 1; i >= 0; i--) {
					const sr = entry.sonarRings[i];
					const age = time - sr.userData.bornAt;
					const t = age / sr.userData.life;
					if (t >= 1) {
						tokensGroup.remove(sr);
						sr.geometry.dispose();
						sr.material.dispose();
						entry.sonarRings.splice(i, 1);
						continue;
					}
					const scale = 1 + t * 2.6;
					sr.scale.setScalar(scale);
					sr.material.opacity = 0.55 * (1 - t);
					sr.position.copy(entry.mesh.position);
					sr.lookAt(camera.position);
				}

				// Position the always-on label just above the sphere, facing camera.
				if (entry.label) {
					const r = entry.radius * entry.hoverScale;
					entry.label.position.set(
						entry.mesh.position.x,
						entry.mesh.position.y + r + 1.4,
						entry.mesh.position.z
					);
				}
			});

			// Finalize feed-mode evictions whose fade just completed.
			if (evictedThisFrame.length) {
				for (const e of evictedThisFrame) {
					const mint = e.data?.mint;
					removeEntry(e);
					if (mint) {
						const idx = state.all.findIndex((t) => t.mint === mint);
						if (idx >= 0) state.all.splice(idx, 1);
					}
				}
				if (state.mode === 'feed') {
					applyFilterAndRender();
					updateStats();
				}
			}

			// Hover raycast — every 2nd frame, only against visible & spawned meshes.
			if (frameCount % 2 === 0) {
				raycaster.setFromCamera(pointer, camera);
				const targets = tokenMeshes.filter((t) => t.visible && t.spawned).map((t) => t.mesh);
				const hits = raycaster.intersectObjects(targets, false);
				if (hits.length) {
					const hit = hits[0].object;
					const entry = tokenMeshes.find((t) => t.mesh === hit);
					setHovered(entry || null);
				} else {
					setHovered(null);
				}
			}

			// Subtle pulse on selected ring.
			if (selected) {
				const s = (selected.hoverScale || 1) * (1 + Math.sin(time * 0.005) * 0.06);
				selected.ring.scale.setScalar(s);
			}

			controls.update();
			composer.render();
		}

		// ── resize ───────────────────────────────────────────────────
		function resize() {
			if (!renderer || !composer) return; // nothing to size in list-view fallback
			const w = host.clientWidth || window.innerWidth;
			const h = host.clientHeight || window.innerHeight;
			renderer.setSize(w, h, false);
			composer.setSize(w, h);
			composer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
			if (bloomPass) bloomPass.setSize(w, h);
			camera.aspect = w / h;
			camera.updateProjectionMatrix();
		}
		window.addEventListener('resize', resize);
		// Respond to container resizes (sidebar toggles, devtools docking, CSS
		// breakpoint reflows) without requiring a reload. rAF-coalesced so a burst
		// of observer callbacks triggers a single renderer/camera update.
		let _resizeRaf = 0;
		if (typeof ResizeObserver !== 'undefined') {
			const ro = new ResizeObserver(() => {
				if (_resizeRaf) return;
				_resizeRaf = requestAnimationFrame(() => { _resizeRaf = 0; resize(); });
			});
			ro.observe(host);
		}
		resize();
		if (webglOK) animate();

		// ── state, filtering, sorting ────────────────────────────────
		// Render style persists across sessions — a viewer who prefers crisp coin
		// logos over wrapped orbs shouldn't have to re-pick it every visit.
		const RENDER_STYLE_KEY = 'vz-render-style';
		function loadRenderStyle() {
			try {
				const v = localStorage.getItem(RENDER_STYLE_KEY);
				return v === 'orb' || v === 'coin' ? v : 'coin';
			} catch { return 'coin'; }
		}
		const state = {
			mode: 'feed',     // 'feed' (live mints) | 'migrations' (live graduations) | 'trending' (top-50 snapshot)
			renderStyle: loadRenderStyle(), // 'coin' (camera-facing logo medallion) | 'orb' (textured sphere)
			all: [],          // raw tokens; in stream modes = recent events, newest first
			sortMode: 'mcap', // 'mcap' | 'live' | 'replies' | 'recent' — trending only
			query: '',
			feed: {
				es: null,
				kind: 'mint',   // 'mint' | 'graduation' — which SSE event stream is open
				retryTimer: null,
				statsTimer: null,
				mintsPerMin: 0,
				gradsPerHour: 0,
				seen: new Map(), // mint → last-seen epoch ms; TTL-bounded (see appendFeedToken)
				everOpened: false,        // ever had a healthy SSE connection
				reconnectAttempts: 0,     // consecutive failed reconnects (reset on open)
				dead: false,              // permanent dead-feed state after the cap
			},
		};

		// A mint may legitimately re-appear in the firehose much later (e.g. a
		// graduation event for a token whose mint we saw days ago). Rather than an
		// arbitrary "drop oldest" Set that lets *recent* tokens re-enter and confuse
		// the viewer, we key by last-seen time: a mint is only re-admitted once it
		// has aged past FEED_SEEN_TTL_MS, and the dedupe Map self-prunes expired
		// entries so it stays bounded without re-admitting fresh ones.
		const FEED_SEEN_TTL_MS = 30 * 60 * 1000;
		const FEED_SEEN_MAX = 8192;

		function sortTokens(tokens, mode) {
			const arr = tokens.slice();
			switch (mode) {
				case 'live':
					arr.sort((a, b) => (Number(!!b.is_currently_live) - Number(!!a.is_currently_live)) || (Number(b.usd_market_cap || 0) - Number(a.usd_market_cap || 0)));
					break;
				case 'replies':
					arr.sort((a, b) => Number(b.reply_count || 0) - Number(a.reply_count || 0));
					break;
				case 'recent':
					arr.sort((a, b) => Number(b.created_timestamp || 0) - Number(a.created_timestamp || 0));
					break;
				default:
					arr.sort((a, b) => Number(b.usd_market_cap || 0) - Number(a.usd_market_cap || 0));
			}
			return arr;
		}

		function filterTokens(tokens, query) {
			const q = query.trim().toLowerCase();
			if (!q) return tokens;
			return tokens.filter((t) => {
				const name = (t.name || '').toLowerCase();
				const sym = (t.symbol || '').toLowerCase();
				const mint = (t.mint || '').toLowerCase();
				return name.includes(q) || sym.includes(q) || mint.includes(q);
			});
		}

		function applyFilterAndRender() {
			// The list-view fallback is the primary surface, so it shows a deeper feed
			// (the 3D scene caps the legend to keep the overlay compact).
			const streamCap = webglOK ? 20 : 80;
			if (state.mode === 'feed' || state.mode === 'migrations') {
				// In stream modes `state.all` is already newest-first; no re-sort.
				const filtered = filterTokens(state.all, state.query);
				applyVisibility(filtered.map((t) => t.mint));
				renderLegend(filtered.slice(0, streamCap));
				return;
			}
			const sorted = sortTokens(state.all, state.sortMode);
			const filtered = filterTokens(sorted, state.query);
			applyVisibility(filtered.map((t) => t.mint));
			renderLegend(filtered);
		}

		function updateStats() {
			if (state.mode === 'feed') {
				statCountEl.textContent = tokenMeshes.length;
				statRateEl.textContent = state.feed.mintsPerMin || NO_VALUE;
				setRateUnit(false);
				statusText.textContent = 'pump.fun firehose · live mints';
				return;
			}
			if (state.mode === 'migrations') {
				statCountEl.textContent = tokenMeshes.length;
				statRateEl.textContent = state.feed.gradsPerHour || NO_VALUE;
				setRateUnit(true);
				statusText.textContent = 'pump.fun firehose · live migrations';
				return;
			}
			const liveTokens = state.all.filter((t) => t.is_currently_live).length;
			statCountEl.textContent = state.all.length;
			const total = state.all.reduce((s, t) => s + (Number(t.usd_market_cap) || 0), 0);
			statMcapEl.textContent = formatMcap(total);
			statusText.textContent = liveTokens > 0
				? `${liveTokens} streaming · pump.fun`
				: `top 50 by market cap · pump.fun`;
		}

		// ── live feed (SSE firehose) ─────────────────────────────────
		// Streams new mints from /api/agents/pumpfun-feed (PumpPortal WS bridge).
		// Each mint → one sphere appended; oldest fades out at FEED_CAP. The mode
		// is the page default — "Trending" is the alt cached snapshot view.

		function feedRadius(mcUsd) {
			const n = Math.max(1, Number(mcUsd) || 0);
			const t = Math.max(0, Math.min(1, (Math.log10(n) - FEED_LIVE_MIN_LOG) / (FEED_LIVE_MAX_LOG - FEED_LIVE_MIN_LOG)));
			return MIN_TOKEN_R + t * (MAX_TOKEN_R - MIN_TOKEN_R);
		}

		function randomShellPoint() {
			// Uniform random point on the unit sphere (Marsaglia).
			const theta = Math.random() * Math.PI * 2;
			const z = Math.random() * 2 - 1;
			const r = Math.sqrt(1 - z * z);
			return { x: Math.cos(theta) * r, y: z, z: Math.sin(theta) * r };
		}

		// Normalize a PumpPortal mint event into the same token shape the rest of
		// the viewer (renderDetail, renderLegend, tooltip) already speaks.
		function normalizeFeedMint(d) {
			const mc = Number(d.market_cap_usd) > 0
				? Number(d.market_cap_usd)
				: (Number(d.market_cap_sol) > 0 && Number(d.sol_price) > 0)
					? Number(d.market_cap_sol) * Number(d.sol_price)
					: null;
			return {
				mint: d.mint,
				name: d.name,
				symbol: d.symbol,
				usd_market_cap: mc,
				market_cap: mc,
				ath_market_cap: mc,
				reply_count: null,
				created_timestamp: d.created_at ? Number(d.created_at) * 1000 : Date.now(),
				image_uri: d.image_uri || null,
				description: d.description || null,
				twitter: d.twitter || null,
				telegram: d.telegram || null,
				website: d.website || null,
				creator: d.creator || null,
				creator_launches: d.creator_launches ?? null,
				creator_graduated: d.creator_graduated ?? null,
				is_currently_live: true,          // visual: red glow + sonar = fresh mint
				signature: d.signature || null,
				replay: !!d.replay,
			};
		}

		// Normalize a PumpPortal migration event (graduation to Raydium/PumpSwap).
		// Re-uses the same token shape; visually distinguished by `is_migration`
		// → green glow + green sonar.
		function normalizeFeedGraduation(d) {
			const mc = Number(d.usd_market_cap) > 0 ? Number(d.usd_market_cap)
				: Number(d.market_cap) > 0 ? Number(d.market_cap)
				: null;
			const ath = Number(d.ath_market_cap) > 0 ? Number(d.ath_market_cap) : mc;
			// Prefer the token's own creation timestamp for the Age stat — it tells
			// the viewer how long this token lived on the bonding curve before
			// graduating. Falls back to the migration timestamp if unavailable.
			const createdMs = d.created_at ? Number(d.created_at) * 1000
				: d.timestamp ? Number(d.timestamp) * 1000
				: Date.now();
			return {
				mint: d.mint,
				name: d.name,
				symbol: d.symbol,
				usd_market_cap: mc,
				market_cap: mc,
				ath_market_cap: ath,
				reply_count: typeof d.reply_count === 'number' ? d.reply_count : null,
				created_timestamp: createdMs,
				image_uri: d.image_uri || null,
				description: d.description || null,
				twitter: d.twitter || null,
				telegram: d.telegram || null,
				website: d.website || null,
				creator: d.creator || null,
				creator_launches: d.creator_launches ?? null,
				creator_graduated: d.creator_graduated ?? null,
				is_currently_live: true,          // visual: green glow + sonar
				is_migration: true,
				pool: d.pool || null,
				raydium_pool: d.raydium_pool || null,
				pump_swap_pool: d.pump_swap_pool || null,
				amount_sol: d.amount_sol ?? null,
				amount_usd: d.amount_usd ?? null,
				migration_at: d.timestamp ? Number(d.timestamp) * 1000 : Date.now(),
				signature: d.signature || d.tx_signature || null,
				replay: !!d.replay,
			};
		}

		function appendFeedToken(token) {
			if (!token.mint) return;
			const now = Date.now();
			const lastSeen = state.feed.seen.get(token.mint);
			if (lastSeen != null && now - lastSeen < FEED_SEEN_TTL_MS) {
				// Still within the dedupe window — refresh recency and skip the dupe.
				state.feed.seen.set(token.mint, now);
				return;
			}
			// New mint, or one that has aged past the TTL → admit and mark recency.
			state.feed.seen.set(token.mint, now);
			// Prune entries older than the TTL; only fall back to evicting the very
			// oldest if the Map is still over the hard cap after expiry pruning.
			if (state.feed.seen.size > FEED_SEEN_MAX) {
				for (const [mint, ts] of state.feed.seen) {
					if (now - ts >= FEED_SEEN_TTL_MS) state.feed.seen.delete(mint);
				}
				while (state.feed.seen.size > FEED_SEEN_MAX) {
					const oldest = state.feed.seen.keys().next().value;
					if (oldest === undefined) break;
					state.feed.seen.delete(oldest);
				}
			}
			// List-view fallback: keep the data flowing into state.all (and the
			// legend) but skip all GPU mesh allocation.
			if (!webglOK) {
				state.all.unshift(token);
				if (state.all.length > FEED_CAP * 2) state.all.length = FEED_CAP * 2;
				return;
			}
			const p = randomShellPoint();
			const shellR = SPHERE_RADIUS * (0.80 + Math.random() * 0.22);
			const position = new THREE.Vector3(p.x * shellR, p.y * shellR, p.z * shellR);
			const radius = feedRadius(token.usd_market_cap);
			const { mesh, ring, tier, cage, rim } = buildTokenMesh(token, position, radius);
			tokensGroup.add(mesh);
			tokensGroup.add(ring);
			const entry = {
				mesh, ring, data: token,
				baseScale: 1, radius,
				isLive: true,
				tier, cage, rim,
				style: state.renderStyle,
				spawnAt: performance.now(),
				spawned: false,
				hoverScale: 1,
				surge: 1,
				visible: true,
				label: null,
				labelOffset: radius + 1.6,
				sonarRings: [],
				nextSonarAt: 0,
				deltaPct: 0,
				flashAt: 0,
				fadeOutAt: 0,
			};
			tokenMeshes.push(entry);
			seedSonarRing(entry);
			state.all.unshift(token);
			if (state.all.length > FEED_CAP * 2) state.all.length = FEED_CAP * 2;
			evictExcessFeedTokens();
		}

		function evictExcessFeedTokens() {
			// Pick the oldest tokens (by spawnAt) that aren't already fading and
			// flag them — the animation loop handles the fade + final removal.
			const active = tokenMeshes.filter((e) => !e.fadeOutAt);
			if (active.length <= FEED_CAP) return;
			active.sort((a, b) => a.spawnAt - b.spawnAt);
			const drop = active.slice(0, active.length - FEED_CAP);
			const now = performance.now();
			for (const e of drop) e.fadeOutAt = now;
		}

		function removeEntry(entry) {
			const idx = tokenMeshes.indexOf(entry);
			if (idx >= 0) tokenMeshes.splice(idx, 1);
			if (selected === entry) clearSelection();
			if (hovered === entry) setHovered(null);
			tokensGroup.remove(entry.mesh);
			tokensGroup.remove(entry.ring);
			if (entry.label) {
				tokensGroup.remove(entry.label);
				if (entry.label.material.map) entry.label.material.map.dispose();
				entry.label.material.dispose();
				entry.label = null;
			}
			for (const sr of entry.sonarRings) {
				tokensGroup.remove(sr);
				sr.geometry.dispose();
				sr.material.dispose();
			}
			entry.sonarRings.length = 0;
			if (entry.cage) {
				entry.cage.geometry.dispose();
				entry.cage.material.dispose();
				entry.cage = null;
			}
			if (entry.rim) {
				entry.rim.geometry.dispose();
				entry.rim.material.dispose();
				entry.rim = null;
			}
			if (entry.mesh.geometry) entry.mesh.geometry.dispose();
			if (entry.mesh.material) {
				if (entry.mesh.material.map) entry.mesh.material.map.dispose();
				entry.mesh.material.dispose();
			}
			if (entry.ring.geometry) entry.ring.geometry.dispose();
			if (entry.ring.material) entry.ring.material.dispose();
		}

		function clearAllTokens() {
			// Iterate a copy because removeEntry mutates tokenMeshes.
			for (const e of tokenMeshes.slice()) removeEntry(e);
			state.feed.seen.clear();
			state.all = [];
		}

		function connectFeed() {
			disconnectFeed();
			state.feed.dead = false;
			hideFeedDeadState();
			const kind = state.feed.kind;
			const url = kind === 'graduation' ? MIGRATIONS_FEED_API : LIVE_FEED_API;
			const eventName = kind === 'graduation' ? 'graduation' : 'mint';
			const normalize = kind === 'graduation' ? normalizeFeedGraduation : normalizeFeedMint;
			const es = new EventSource(url);
			state.feed.es = es;
			// Did *this* connection ever open? A clean 90s server cycle (opened then
			// closed) is healthy and must not count toward the failure cap.
			let thisOpened = false;
			es.addEventListener('open', () => {
				thisOpened = true;
				state.feed.everOpened = true;
				state.feed.reconnectAttempts = 0; // healthy connection clears backoff
				if (firstLoad) revealVisualizer();
				statusEl.dataset.state = 'ready';
				updateStats();
			});
			es.addEventListener(eventName, (msg) => {
				// Bail if the user has switched modes since this listener was wired.
				if (state.feed.kind !== kind) return;
				let raw;
				try { raw = JSON.parse(msg.data); } catch { return; }
				const token = normalize(raw);
				appendFeedToken(token);
				applyFilterAndRender();
				updateStats();
				state.feed.everOpened = true;
				if (firstLoad) revealVisualizer();
			});
			// Server keeps SSE open for 90s then sends `close` — we reconnect.
			es.addEventListener('close', () => scheduleFeedReconnect(thisOpened));
			es.addEventListener('error', () => {
				if (es.readyState === EventSource.CLOSED) scheduleFeedReconnect(thisOpened);
				// Don't surface "unreachable" once we've had a working connection —
				// transient reconnects are normal (server cycles every 90s).
				else if (!state.feed.everOpened) {
					statusEl.dataset.state = 'error';
					statusText.textContent = 'Feed unreachable, retrying…';
				}
			});
		}

		function disconnectFeed() {
			if (state.feed.es) { try { state.feed.es.close(); } catch {} state.feed.es = null; }
			clearTimeout(state.feed.retryTimer);
			state.feed.retryTimer = null;
		}

		// Exponential backoff with a hard cap on both the delay and the attempt
		// count. A connection that opened cleanly (the normal 90s cycle) reconnects
		// immediately and resets backoff; only never-opened failures escalate the
		// delay, and after the cap we enter a permanent dead-feed state.
		function scheduleFeedReconnect(connectionWasHealthy) {
			if (state.mode !== 'feed' && state.mode !== 'migrations') return;
			clearTimeout(state.feed.retryTimer);
			if (connectionWasHealthy) {
				// Healthy cycle → quick reconnect, no penalty.
				state.feed.reconnectAttempts = 0;
				state.feed.retryTimer = setTimeout(connectFeed, FEED_BASE_BACKOFF_MS);
				return;
			}
			if (state.feed.reconnectAttempts >= FEED_MAX_RECONNECT_ATTEMPTS) {
				enterFeedDeadState();
				return;
			}
			const delay = Math.min(
				FEED_BASE_BACKOFF_MS * 2 ** state.feed.reconnectAttempts,
				FEED_MAX_BACKOFF_MS,
			);
			state.feed.reconnectAttempts++;
			statusEl.dataset.state = 'error';
			statusText.textContent = `Feed unreachable · retrying in ${Math.round(delay / 1000)}s (${state.feed.reconnectAttempts}/${FEED_MAX_RECONNECT_ATTEMPTS})`;
			state.feed.retryTimer = setTimeout(connectFeed, delay);
		}

		// Permanent dead-feed state: stop auto-retrying and offer a manual Reconnect.
		function enterFeedDeadState() {
			disconnectFeed();
			state.feed.dead = true;
			statusEl.dataset.state = 'error';
			statusText.textContent = 'Live feed offline';
			errorMessage.textContent = 'Could not reach the pump.fun firehose after several attempts. PumpPortal may be temporarily down.';
			const retry = document.getElementById('vz-error-retry');
			if (retry) retry.textContent = 'Reconnect';
			const heading = errorEl.querySelector('h3');
			if (heading) heading.textContent = 'Live feed offline';
			errorEl.hidden = false;
		}

		// Clear a previously-raised dead-feed error box and restore the trending
		// error copy, so a fresh connect attempt starts from a clean slate.
		function hideFeedDeadState() {
			if (errorEl.hidden) return;
			errorEl.hidden = true;
			const heading = errorEl.querySelector('h3');
			if (heading) heading.textContent = 'Could not load trending tokens';
			const retry = document.getElementById('vz-error-retry');
			if (retry) retry.textContent = 'Retry';
		}

		// Manual reconnect from the dead-feed state — reset the backoff and retry.
		// connectFeed() clears the dead-feed error box via hideFeedDeadState().
		function manualReconnectFeed() {
			state.feed.reconnectAttempts = 0;
			statusEl.dataset.state = 'loading';
			statusText.textContent = 'Reconnecting to pump.fun firehose…';
			connectFeed();
		}

		async function tickFeedStats() {
			if (state.mode !== 'feed' && state.mode !== 'migrations') return;
			try {
				const r = await fetch(STATS_API, { headers: { accept: 'application/json' } });
				if (!r.ok) return;
				const d = await r.json();
				state.feed.mintsPerMin = Number(d?.feed?.mints_per_min) || 0;
				state.feed.gradsPerHour = Number(d?.feed?.graduations_per_hour) || 0;
				updateStats();
			} catch {}
		}

		function revealVisualizer() {
			if (!firstLoad) return;
			firstLoad = false;
			controlsEl.hidden = false;
			rampEl.hidden = false;
			introEl.classList.add('is-hidden');
			setTimeout(() => { try { introEl.remove(); } catch {} }, 900);
			startIntroFlyIn();
		}

		function enterFeedMode() {
			state.mode = 'feed';
			state.feed.kind = 'mint';
			controlsEl.dataset.mode = 'feed';
			statusEl.dataset.mode = 'feed';
			modeBtns.forEach((b) => b.classList.toggle('is-active', b.dataset.mode === 'feed'));
			clearInterval(refreshTimer);
			refreshBtn.disabled = true;
			errorEl.hidden = true;
			clearAllTokens();
			state.feed.everOpened = false;
			state.feed.reconnectAttempts = 0;
			state.feed.dead = false;
			legendHeadEl.textContent = 'Latest mints';
			statusEl.dataset.state = firstLoad ? 'loading' : 'ready';
			statusText.textContent = firstLoad ? 'Connecting to pump.fun firehose…' : 'pump.fun firehose · live mints';
			updateStats();
			connectFeed();
			clearInterval(state.feed.statsTimer);
			tickFeedStats();
			state.feed.statsTimer = setInterval(tickFeedStats, STATS_INTERVAL_MS);
		}

		// Backfill the migrations feed with the most-recent enriched graduations
		// from Postgres (or the WS feed's ring buffer) so the canvas never opens
		// blank — graduations can be minutes apart on a slow stretch.
		async function backfillMigrations() {
			try {
				const r = await fetch(MIGRATIONS_BACKFILL_API, { headers: { accept: 'application/json' } });
				if (!r.ok) return;
				const d = await r.json();
				const items = Array.isArray(d?.items) ? d.items : [];
				// Oldest first so each unshift puts the newest on top.
				for (let i = items.length - 1; i >= 0; i--) {
					if (state.mode !== 'migrations') return; // user switched away mid-fetch
					const token = normalizeFeedGraduation({ ...items[i], replay: true });
					appendFeedToken(token);
				}
				applyFilterAndRender();
				updateStats();
			} catch {}
		}

		function enterMigrationsMode() {
			state.mode = 'migrations';
			state.feed.kind = 'graduation';
			controlsEl.dataset.mode = 'migrations';
			statusEl.dataset.mode = 'migrations';
			modeBtns.forEach((b) => b.classList.toggle('is-active', b.dataset.mode === 'migrations'));
			clearInterval(refreshTimer);
			refreshBtn.disabled = true;
			errorEl.hidden = true;
			clearAllTokens();
			state.feed.everOpened = false;
			state.feed.reconnectAttempts = 0;
			state.feed.dead = false;
			legendHeadEl.textContent = 'Latest migrations';
			statusEl.dataset.state = firstLoad ? 'loading' : 'ready';
			statusText.textContent = firstLoad ? 'Connecting to pump.fun firehose…' : 'pump.fun firehose · live migrations';
			updateStats();
			backfillMigrations();
			connectFeed();
			clearInterval(state.feed.statsTimer);
			tickFeedStats();
			state.feed.statsTimer = setInterval(tickFeedStats, STATS_INTERVAL_MS);
		}

		function enterTrendingMode() {
			state.mode = 'trending';
			controlsEl.dataset.mode = 'trending';
			statusEl.dataset.mode = 'trending';
			modeBtns.forEach((b) => b.classList.toggle('is-active', b.dataset.mode === 'trending'));
			disconnectFeed();
			state.feed.dead = false;
			clearInterval(state.feed.statsTimer);
			state.feed.statsTimer = null;
			clearAllTokens();
			// Restore the trending error copy in case a dead-feed state edited it.
			const heading = errorEl.querySelector('h3');
			if (heading) heading.textContent = 'Could not load trending tokens';
			const retry = document.getElementById('vz-error-retry');
			if (retry) retry.textContent = 'Retry';
			legendHeadEl.textContent = 'Top 20 by Market Cap';
			loadData();
		}

		// Mode toggle wiring.
		modeBtns.forEach((btn) => {
			btn.addEventListener('click', () => {
				const m = btn.dataset.mode;
				if (state.mode === m) return;
				if (m === 'feed') enterFeedMode();
				else if (m === 'migrations') enterMigrationsMode();
				else enterTrendingMode();
			});
		});

		// Search wiring (debounced).
		let searchDebounce = null;
		searchInput.addEventListener('input', () => {
			clearTimeout(searchDebounce);
			searchDebounce = setTimeout(() => {
				state.query = searchInput.value;
				applyFilterAndRender();
			}, 90);
		});

		// Sort wiring.
		sortBtns.forEach((btn) => {
			btn.addEventListener('click', () => {
				const mode = btn.dataset.sort;
				if (state.sortMode === mode) return;
				state.sortMode = mode;
				sortBtns.forEach((b) => b.classList.toggle('is-active', b === btn));
				applyFilterAndRender();
			});
		});

		// ── Render-style toggle (Coins ⟷ Orbs) ──────────────────────
		// Rebuild every live mesh in place — same data, same shell positions — so a
		// style switch is instant and never drops the user's place in the feed.
		// Preserves any open detail selection across the swap.
		function rebuildMeshesForStyle() {
			if (!webglOK) return; // list-view fallback is unaffected by 3D style
			const snapshots = tokenMeshes.map((e) => ({
				data: e.data,
				position: e.mesh.position.clone(),
				radius: e.radius,
				isLive: e.isLive,
				deltaPct: e.deltaPct,
				visible: e.visible,
			}));
			const selMint = selected?.data?.mint || null;
			const detailWasOpen = detailEl.classList.contains('is-open');
			for (const e of tokenMeshes.slice()) removeEntry(e);

			for (const s of snapshots) {
				const { mesh, ring, isLive, tier, cage, rim } = buildTokenMesh(s.data, s.position, s.radius);
				mesh.scale.setScalar(1);
				ring.scale.setScalar(1);
				mesh.visible = s.visible;
				ring.visible = s.visible;
				tokensGroup.add(mesh);
				tokensGroup.add(ring);
				const entry = {
					mesh, ring, data: s.data,
					baseScale: 1, radius: s.radius,
					isLive,
					tier, cage, rim,
					style: state.renderStyle,
					spawnAt: performance.now() - 1000, // already on-screen → skip pop-in
					spawned: true,
					hoverScale: 1,
					surge: 1,
					visible: s.visible,
					label: null,
					labelOffset: s.radius + 1.6,
					sonarRings: [],
					nextSonarAt: 0,
					deltaPct: s.deltaPct,
					flashAt: 0,
					fadeOutAt: 0,
				};
				tokenMeshes.push(entry);
				if (isLive) seedSonarRing(entry);
			}
			applyFilterAndRender();
			if (detailWasOpen && selMint) {
				const tok = state.all.find((t) => t.mint === selMint);
				if (tok) selectToken(tok);
			}
		}

		function setRenderStyle(style, persist = true) {
			if (style !== 'coin' && style !== 'orb') return;
			const changed = state.renderStyle !== style;
			state.renderStyle = style;
			styleBtns.forEach((b) => {
				const on = b.dataset.style === style;
				b.classList.toggle('is-active', on);
				b.setAttribute('aria-selected', String(on));
			});
			if (persist) { try { localStorage.setItem(RENDER_STYLE_KEY, style); } catch {} }
			if (changed) rebuildMeshesForStyle();
		}

		styleBtns.forEach((btn) => {
			btn.addEventListener('click', () => setRenderStyle(btn.dataset.style));
		});
		// Reflect the persisted style on the toggle at boot (no meshes exist yet, so
		// no rebuild is forced).
		setRenderStyle(state.renderStyle, false);

		// Hint dismiss.
		hintDismiss.addEventListener('click', () => {
			hintEl.classList.add('is-hidden');
			try { localStorage.setItem('vz-hint-dismissed', '1'); } catch {}
		});
		try {
			if (localStorage.getItem('vz-hint-dismissed') === '1') hintEl.classList.add('is-hidden');
		} catch {}

		// ── data loading ─────────────────────────────────────────────
		let refreshTimer = null;
		let nextRefreshAt = 0;
		let firstLoad = true;

		function scheduleNextRefresh() {
			clearInterval(refreshTimer);
			nextRefreshAt = Date.now() + REFRESH_INTERVAL_MS;
			updateCountdown();
			refreshTimer = setInterval(() => {
				const remaining = Math.max(0, nextRefreshAt - Date.now());
				updateCountdown();
				if (remaining <= 0) {
					loadData(true);
				}
			}, 1000);
		}

		function updateCountdown() {
			const remaining = Math.max(0, Math.ceil((nextRefreshAt - Date.now()) / 1000));
			countdownEl.textContent = remaining + 's';
		}

		async function loadData(silent = false) {
			if (!silent) {
				statusEl.dataset.state = 'loading';
				statusText.textContent = 'Loading trending tokens…';
				countdownEl.textContent = '…';
			}
			refreshBtn.disabled = true;
			errorEl.hidden = true;
			try {
				const resp = await fetch(TRENDING_API, { headers: { accept: 'application/json' } });
				if (!resp.ok) throw new Error(`API returned ${resp.status}`);
				const payload = await resp.json();
				// Rich trending is wrapped as { data: [...] }; tolerate a bare array
				// too so the viewer survives any future shape change upstream.
				const data = Array.isArray(payload) ? payload
					: Array.isArray(payload?.data) ? payload.data
					: [];
				if (!data.length) throw new Error('No trending tokens returned');

				state.all = data;
				const sorted = sortTokens(state.all, state.sortMode);
				placeTokens(sorted);
				applyFilterAndRender();
				updateStats();
				statusEl.dataset.state = 'ready';
				refreshBtn.disabled = false;
				controlsEl.hidden = false;
				rampEl.hidden = false;

				if (firstLoad) {
					firstLoad = false;
					introEl.classList.add('is-hidden');
					setTimeout(() => { introEl.remove(); }, 900);
					startIntroFlyIn();
				}

				scheduleNextRefresh();
			} catch (err) {
				console.error('[pump-visualizer] load failed', err);
				statusEl.dataset.state = 'error';
				statusText.textContent = 'Failed to load';
				refreshBtn.disabled = false;
				countdownEl.textContent = '!';
				errorMessage.textContent = err.message || 'Unknown error';
				errorEl.hidden = false;
				introEl.classList.add('is-hidden');
			}
		}

		refreshBtn.addEventListener('click', () => {
			if (refreshBtn.disabled) return;
			clearSelection();
			loadData();
		});
		// The error box is shared: in trending mode "Retry" reloads the snapshot; in
		// a live-stream dead-feed state it manually reconnects the SSE firehose.
		errorRetry.addEventListener('click', () => {
			if ((state.mode === 'feed' || state.mode === 'migrations') && state.feed.dead) {
				manualReconnectFeed();
			} else {
				loadData();
			}
		});

		// Pause auto-refresh / live feed when tab is hidden; resume on focus.
		document.addEventListener('visibilitychange', () => {
			const isStream = state.mode === 'feed' || state.mode === 'migrations';
			if (document.hidden) {
				clearInterval(refreshTimer);
				if (isStream) {
					disconnectFeed();
					clearInterval(state.feed.statsTimer);
					state.feed.statsTimer = null;
				}
			} else if (isStream) {
				connectFeed();
				clearInterval(state.feed.statsTimer);
				tickFeedStats();
				state.feed.statsTimer = setInterval(tickFeedStats, STATS_INTERVAL_MS);
			} else if (nextRefreshAt && !firstLoad) {
				if (Date.now() >= nextRefreshAt) loadData(true);
				else scheduleNextRefresh();
			}
		});

		// Market-cap tier key — built once from the same ladder the scene uses.
		const rampEl = document.getElementById('vz-ramp');
		(function buildTierRamp() {
			const host = document.getElementById('vz-ramp-tiers');
			const hex = (n) => '#' + n.toString(16).padStart(6, '0');
			const fmt = (v) => formatMcap(v).replace('.0', '');
			MCAP_TIERS.forEach((t, i) => {
				const next = MCAP_TIERS[i + 1];
				const row = document.createElement('div');
				row.className = 'tier';
				const sw = document.createElement('span');
				sw.className = 'sw';
				sw.style.background = hex(t.color);
				sw.style.boxShadow = `0 0 8px ${hex(t.color)}`;
				const nm = document.createElement('span');
				nm.className = 'nm';
				nm.textContent = t.name;
				const th = document.createElement('span');
				th.className = 'th';
				if (t.min === 0) th.textContent = '< ' + fmt(next.min);
				else if (next) th.textContent = fmt(t.min) + '–' + fmt(next.min);
				else th.textContent = fmt(t.min) + '+';
				row.append(sw, nm, th);
				host.appendChild(row);
			});
		})();

		// "Try 3D again" reloads the page so WebGL init runs fresh — the most
		// reliable way to recover a usable context after a software-block lifts or a
		// GPU reset clears.
		const fallbackRetryBtn = document.getElementById('vz-fallback-retry');
		if (fallbackRetryBtn) fallbackRetryBtn.addEventListener('click', () => window.location.reload());

		// If WebGL never came up, switch to the list view before booting the feed so
		// the very first event renders into the legend instead of a blank canvas.
		if (!webglOK) enterListFallback();

		// Boot in live-firehose mode.
		enterFeedMode();
	</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>