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.

204 KB
Raw Blame
<!doctype html>
<html lang="en" class="pump-dashboard-page">
	<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" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title data-i18n="pump_dashboard.meta_title">Pump Dashboard — three.ws</title>
		<meta
			name="description"
			content="Real-time Pump.fun dashboard — live feed, watch list, claims, token scanner, quoting, vanity addresses."
		 data-i18n-attr="content:pump_dashboard.meta_description"/>
		<meta name="theme-color" content="#070707" />
		<link rel="canonical" href="https://three.ws/pump-dashboard" />

		<meta property="og:type" content="website" />
		<meta property="og:site_name" content="three.ws" />
		<meta property="og:title" content="Pump Dashboard — three.ws"  data-i18n-attr="content:pump_dashboard.meta_og_title"/>
		<meta
			property="og:description"
			content="Real-time Pump.fun dashboard — live feed, watch list, claims, token scanner, quoting, vanity addresses."
		 data-i18n-attr="content:pump_dashboard.meta_og_description"/>
		<meta property="og:url" content="https://three.ws/pump-dashboard" />
		<meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Pump+Dashboard&amp;d=Pump.fun+trading+desk%3A+watchlists%2C+scanner%2C+quotes%2C+portfolio%2C+and+live+charts.&amp;p=%2Fpump-dashboard" />

		<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" />
		<link rel="stylesheet" href="/style.css" />
		<link rel="stylesheet" href="/nav.css" />
		<link rel="stylesheet" href="/home.css" />
		<link rel="stylesheet" href="/footer.css" />
		<link rel="stylesheet" href="/fonts/fonts.css" />
		<link rel="stylesheet" href="/pump-dashboard.css" />
		<link rel="stylesheet" href="/mobile.css" />
		<script defer src="/nav.js"></script>
		<script defer src="/footer-newsletter.js"></script>
		<script
			type="module"
			src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"
			integrity="sha384-wjsPzEO+lXOf7d9csIDfAQpPt2OKuUU3m0K9qsdKIuzX4N8czSF6hdh23eAbZa3p"
			crossorigin="anonymous"
		></script>
		<style>
			/* Config connection-test pills (Task 10) */
			.pd-probe {
				display: inline-block;
				margin-left: 0.4rem;
				font-size: 0.66rem;
				font-weight: 600;
				padding: 0.05rem 0.45rem;
				border-radius: 999px;
				vertical-align: middle;
			}
			.pd-probe.is-ok {
				color: var(--success);
				background: rgba(74, 222, 128, 0.14);
				border: 1px solid rgba(74, 222, 128, 0.3);
			}
			.pd-probe.is-err {
				color: var(--danger);
				background: rgba(248, 113, 113, 0.14);
				border: 1px solid rgba(248, 113, 113, 0.32);
			}
			.pd-probe.is-pending {
				color: var(--warn);
				background: rgba(251, 191, 36, 0.14);
				border: 1px solid rgba(251, 191, 36, 0.3);
			}
			/* Stale monitor stat cards (Task 07) */
			.pd-stat.is-stale {
				opacity: 0.5;
			}
			.pd-stale-badge {
				display: inline-block;
				font-size: 0.58rem;
				color: var(--warn);
				margin-left: 0.35rem;
				text-transform: uppercase;
				letter-spacing: 0.05em;
				vertical-align: middle;
			}
			/* Wallet holdings token logos (Task 02) */
			.pd-token-logo {
				width: 18px;
				height: 18px;
				border-radius: 50%;
				vertical-align: middle;
				margin-right: 0.4rem;
				object-fit: cover;
				background: var(--surface-1);
			}
			#pd-market-chart {
				cursor: crosshair;
			}
			/* Recoverable feed-error banner (WS dead-feed + channel-feed failure) */
			.pd-feed-error {
				margin: 0.75rem;
				padding: 0.9rem 1rem;
				border: 1px solid rgba(248, 113, 113, 0.45);
				border-radius: 10px;
				background: rgba(248, 113, 113, 0.09);
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				gap: 0.5rem;
			}
			.pd-feed-error-title {
				font-family: var(--font-display);
				font-size: 0.82rem;
				font-weight: 600;
				letter-spacing: 0.02em;
				color: var(--danger);
			}
			.pd-feed-error-msg {
				font-size: 0.8rem;
				line-height: 1.45;
				color: var(--ink-dim);
			}
			.pd-feed-error .pd-btn {
				margin-top: 0.15rem;
			}
			/* RPC-failure flag on the network panel's RPC sub-line */
			.pd-stat-sub.is-danger {
				color: var(--danger);
			}
			/* Oracle conviction panel */
			.pd-oracle-live-dot {
				display: inline-block; width: 7px; height: 7px; border-radius: 50%;
				background: #a07bff; margin-left: 6px; vertical-align: middle;
				box-shadow: 0 0 0 0 rgba(160,123,255,.4);
				animation: pd-oracle-pulse 2.4s ease-out infinite;
			}
			@keyframes pd-oracle-pulse {
				0% { box-shadow: 0 0 0 0 rgba(160,123,255,.45); }
				70% { box-shadow: 0 0 0 7px rgba(160,123,255,0); }
				100% { box-shadow: 0 0 0 0 rgba(160,123,255,0); }
			}
			.pd-oracle-feed { display: flex; flex-direction: column; gap: 1px; background: var(--line, rgba(255,255,255,.07)); max-height: 360px; overflow-y: auto; }
			.pd-oracle-item { display: grid; grid-template-columns: 44px 1fr auto; align-items: center; gap: 10px; padding: 10px 14px; background: var(--surface-0, #0d0f14); text-decoration: none; color: inherit; transition: background var(--duration-fast); }
			.pd-oracle-item:hover { background: rgba(255,255,255,.04); }
			.pd-oracle-score-col { display: flex; flex-direction: column; align-items: center; line-height: 1; }
			.pd-oracle-score-num { font: 800 18px/1 var(--font-mono, monospace); }
			.pd-oracle-score-label { font-size: 8px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted, #888); margin-top: 2px; }
			.pd-oracle-info { min-width: 0; }
			.pd-oracle-sym { font-weight: 700; font-size: 13.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
			.pd-oracle-name { font-size: 11px; color: var(--muted, #888); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
			.pd-oracle-pillars { display: flex; gap: 3px; margin-top: 4px; }
			.pd-oracle-bar { width: 28px; height: 3px; border-radius: 99px; background: rgba(255,255,255,.1); overflow: hidden; }
			.pd-oracle-bar-fill { height: 100%; border-radius: 99px; }
			.pd-oracle-tier-badge { font-size: 9.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; padding: 2px 7px; border-radius: 99px; border: 1px solid; flex-shrink: 0; align-self: flex-start; }
			.pd-oracle-empty { padding: 24px 14px; text-align: center; color: var(--muted, #888); font-size: 12.5px; }
			.pd-oracle-empty a { color: var(--accent, #7c83ff); }
			.pd-oracle-sk { height: 60px; background: linear-gradient(90deg, rgba(255,255,255,.03) 25%, rgba(255,255,255,.06) 37%, rgba(255,255,255,.03) 63%); background-size: 400% 100%; animation: pd-sk 1.4s infinite; border-bottom: 1px solid var(--line, rgba(255,255,255,.07)); }
			@keyframes pd-sk { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
			/* auto-fit keeps the five stats from clipping their labels on a 320px
			   phone, where a fixed 5-column grid gave each cell only 64px. */
			.pd-oracle-stats-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(96px,1fr)); gap:1px; background:var(--line,rgba(255,255,255,.07)); border-bottom:1px solid var(--line,rgba(255,255,255,.07)); }
			.pd-oracle-stat { padding:10px 12px; background:var(--surface-0,#0d0f14); display:flex; flex-direction:column; gap:2px; min-width:0; }
			.pd-oracle-stat-val { font:700 14px/1 var(--font-mono,monospace); color:var(--text,#e8e8e8); }
			.pd-oracle-stat-val.positive { color:#34d399; }
			.pd-oracle-stat-lbl { font-size:9px; text-transform:uppercase; letter-spacing:.07em; color:var(--muted,#888); }
		</style>

		<meta name="twitter:card" content="summary_large_image" />
		<meta name="twitter:title" content="Pump Dashboard · three.ws"  data-i18n-attr="content:pump_dashboard.meta_twitter_title"/>
		<meta
			name="twitter:description"
			content="Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts."
		 data-i18n-attr="content:pump_dashboard.meta_twitter_description"/>
		<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Pump+Dashboard&amp;d=Pump.fun+trading+desk%3A+watchlists%2C+scanner%2C+quotes%2C+portfolio%2C+and+live+charts.&amp;p=%2Fpump-dashboard" />
		<script type="application/ld+json">
			{
				"@context": "https://schema.org",
				"@type": "WebPage",
				"name": "Pump Dashboard",
				"description": "Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.",
				"url": "https://three.ws/pump-dashboard",
				"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 Dashboard — three.ws">
	<meta name="twitter:site" content="@trythreews">
	<script src="/model-viewer-meshopt.js"></script>
</head>
	<body class="home-page pump-dashboard-page">
		<a href="#pd-main" class="h-skip-link" data-i18n="pump_dashboard.skip_to_main_content">Skip to main content</a>

		<header><div id="nav-container"></div></header>

		<div class="pd-app" id="pd-main">
			<aside class="pd-sidebar" id="pd-sidebar">
				<div class="pd-sidebar-head">
					<a class="pd-sidebar-brand" href="/" aria-label="three.ws home" data-i18n-attr="aria-label:pump_dashboard.three_ws_home_arialabel">
						<img
							class="wordmark-logo"
							src="/three.svg"
							alt=""
							aria-hidden="true"
						/>three.ws
					</a>
					<div class="pd-sidebar-eyebrow">Token Cockpit</div>
				</div>
				<nav>
					<div class="pd-nav-section">Overview</div>
					<a href="#dashboard" data-page="dashboard" class="is-active">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<rect x="2" y="2" width="5" height="5" rx="1" />
							<rect x="9" y="2" width="5" height="5" rx="1" />
							<rect x="2" y="9" width="5" height="5" rx="1" />
							<rect x="9" y="9" width="5" height="5" rx="1" />
						</svg>
						Dashboard
					</a>
					<a href="#feed" data-page="feed">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<path d="M2 10c0-3.3 2.7-6 6-6" />
							<path d="M2 6c0-2.2 1.8-4 4-4" />
							<circle cx="3" cy="13" r="1.2" fill="currentColor" stroke="none" />
						</svg>
						Live Feed
					</a>

					<div class="pd-nav-section">Tracking</div>
					<a href="#watches" data-page="watches">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<path d="M1.5 8s2.5-5 6.5-5 6.5 5 6.5 5-2.5 5-6.5 5S1.5 8 1.5 8z" />
							<circle cx="8" cy="8" r="2.2" />
						</svg>
						Watch List
					</a>
					<a href="#claims" data-page="claims">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<circle cx="8" cy="8" r="6" />
							<path d="M5.5 8.5l1.8 1.8L10.8 6.5" />
						</svg>
						Fee Claims
					</a>
					<a href="#alerts" data-page="alerts">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<path d="M3 11c0-3 1-7 5-7s5 4 5 7M2 11h12M7 13h2" />
						</svg>
						Alerts
					</a>

					<div class="pd-nav-section">Tools</div>
					<a href="#scanner" data-page="scanner">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<circle cx="7" cy="7" r="4.5" />
							<path d="M10.5 10.5l3 3" />
						</svg>
						Token Scanner
					</a>
					<a href="#quoting" data-page="quoting">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<path d="M2 12l3-4 3 2 4-6 2 3" />
						</svg>
						Quote Engine
					</a>
					<a href="#vanity" data-page="vanity">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<circle cx="5" cy="11" r="2.5" />
							<path d="M7 9l6-6M11 4l2 2" />
						</svg>
						Vanity Generator
					</a>

					<div class="pd-nav-section">Agent</div>
					<a href="#animations" data-page="animations">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<circle cx="8" cy="5" r="2.5" />
							<path d="M3 14c0-3 2.2-5 5-5s5 2 5 5" />
						</svg>
						Default Agent
					</a>
					<div class="pd-nav-section">System</div>
					<a href="#config" data-page="config">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<circle cx="8" cy="8" r="2" />
							<path
								d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.4 1.4M11.55 11.55l1.4 1.4M3.05 12.95l1.4-1.4M11.55 4.45l1.4-1.4"
							/>
						</svg>
						Configuration
					</a>
					<a href="#api" data-page="api">
						<svg
							viewBox="0 0 16 16"
							fill="none"
							stroke="currentColor"
							stroke-width="1.4"
							aria-hidden="true"
						>
							<rect x="2" y="6" width="5" height="4" rx="1" />
							<path d="M7 8h4M11 6v4M14 6v4M11 6h3M11 10h3" />
						</svg>
						API Reference
					</a>
				</nav>
				<div class="pd-sidebar-foot">
					<a class="pd-sidebar-back" href="/dashboard/tokens" data-i18n="pump_dashboard.back_to_dashboard">&larr; Back to dashboard</a>
					<span id="pd-uptime" data-i18n="pump_dashboard.uptime">Uptime: —</span>
				</div>
			</aside>

			<main class="pd-main">
				<div class="pd-topbar">
					<h1 class="pd-page-title" id="pd-page-title" data-i18n="pump_dashboard.dashboard">Dashboard</h1>
					<div class="pd-spacer"></div>
					<div class="pd-status-chip" title="three.ws API health">
						<span class="pd-dot is-warm" id="pd-api-dot"></span>
						<span id="pd-api-status" data-i18n="pump_dashboard.api_connecting">API: connecting…</span>
					</div>
					<div class="pd-status-chip" title="Pump.fun realtime WebSocket">
						<span class="pd-dot" id="pd-ws-dot"></span>
						<span id="pd-ws-status" data-i18n="pump_dashboard.ws_idle">WS: idle</span>
					</div>
					<div
						class="pd-status-chip"
						id="pd-sol-chip"
						title="SOL spot price (via Helius/Pyth)"
					>
						<span class="pd-dot" id="pd-sol-dot"></span>
						<span id="pd-sol-status" data-i18n="pump_dashboard.sol">SOL: —</span>
					</div>
				</div>

				<!-- ═══════ Dashboard page ═══════ -->
				<section
					class="pd-page is-active"
					id="page-dashboard"
					aria-labelledby="pd-page-title"
				>
					<!-- Bot/monitor stat cards — bound to GET /api/healthz (monitor + watches + uptime). -->
					<div class="pd-stat-grid" id="pd-monitor-stats" style="margin-bottom: 1rem">
						<div class="pd-stat">
							<div class="pd-stat-label">Live monitor</div>
							<div class="pd-stat-value" id="stat-bot-status">—</div>
							<div class="pd-stat-sub" id="stat-bot-status-sub">Realtime tracker</div>
						</div>
						<div class="pd-stat">
							<div class="pd-stat-label">Tracking engine</div>
							<div class="pd-stat-value" id="stat-bot-mode">—</div>
							<div class="pd-stat-sub">Monitor mode</div>
						</div>
						<div class="pd-stat">
							<div class="pd-stat-label">Graduations</div>
							<div class="pd-stat-value" id="stat-claims">—</div>
							<div class="pd-stat-sub">Detected on-chain</div>
						</div>
						<div class="pd-stat">
							<div class="pd-stat-label">Active watches</div>
							<div class="pd-stat-value" id="stat-watches">—</div>
							<div class="pd-stat-sub">Across the network</div>
						</div>
						<div class="pd-stat">
							<div class="pd-stat-label">Uptime</div>
							<div class="pd-stat-value" id="stat-uptime">—</div>
							<div class="pd-stat-sub">Monitor process</div>
						</div>
					</div>
					<div class="pd-dash-grid">
						<div class="pd-panel pd-mod-8">
							<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.featured_agent">Featured agent</h2></div>
							<div class="pd-panel-body">
								<div class="pd-featured" id="pd-featured-card">
									<div class="pd-featured-avatar" id="pd-featured-avatar">
										<model-viewer
											src="/animations/robotexpressive.glb"
											auto-rotate
											auto-rotate-delay="500"
											rotation-per-second="18deg"
											interaction-prompt="none"
											shadow-intensity="0"
											exposure="0.85"
											environment-image="neutral"
											camera-orbit="0deg 80deg 5m"
											field-of-view="35deg"
											loading="lazy"
										></model-viewer>
									</div>
									<div class="pd-featured-info">
										<div class="pd-featured-name" id="pd-featured-name">
											Loading agent…
										</div>
										<p class="pd-featured-desc" id="pd-featured-desc" data-i18n="pump_dashboard.fetching_the_featured_agent_for_this_account">
											Fetching the featured agent for this account.
										</p>
										<div
											class="pd-featured-stats"
											id="pd-featured-stats"
											hidden
										></div>
										<div>
											<a
												class="pd-btn is-primary pd-btn-sm"
												id="pd-featured-link"
												href="/my-agents"
												 data-i18n="pump_dashboard.view_profile">View profile</a
											>
											<a class="pd-btn pd-btn-sm" href="/create"
												 data-i18n="pump_dashboard.create_agent">Create agent</a
											>
										</div>
									</div>
								</div>
							</div>
						</div>

						<div class="pd-panel pd-mod-4">
							<div class="pd-panel-head">
								<h2 data-i18n="pump_dashboard.wallet_snapshot">Wallet snapshot</h2>
								<div class="pd-spacer"></div>
								<button
									class="pd-btn pd-btn-sm"
									id="pd-wallet-disconnect"
									type="button"
									hidden
								 data-i18n="pump_dashboard.disconnect">
									Disconnect
								</button>
							</div>
							<div class="pd-panel-body" id="pd-wallet-body">
								<div class="pd-empty" id="pd-wallet-empty">
									<svg
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										stroke-width="1.5"
										aria-hidden="true"
									>
										<rect x="3" y="6" width="18" height="13" rx="2" />
										<path d="M3 10h18M16 14h2" />
									</svg>
									<div>
										Connect your Solana wallet to see SOL &amp; token holdings.
									</div>
									<div style="margin-top: 0.85rem">
										<button
											class="pd-btn is-primary pd-btn-sm"
											id="connect-wallet-btn"
											type="button"
										 data-i18n="pump_dashboard.connect_wallet">
											Connect Wallet
										</button>
									</div>
								</div>
								<div id="pd-wallet-holdings" hidden></div>
							</div>
						</div>

						<div class="pd-panel pd-mod-6">
							<div class="pd-panel-head">
								<h2 data-i18n="pump_dashboard.network_health">Network health</h2>
								<div class="pd-spacer"></div>
								<span class="pd-badge" id="pd-network-badge">—</span>
							</div>
							<div class="pd-panel-body">
								<div class="pd-stat-grid">
									<div class="pd-stat">
										<div class="pd-stat-label">SOL Price</div>
										<div class="pd-stat-value" id="pd-stat-sol">—</div>
										<div class="pd-stat-sub" id="pd-stat-sol-sub">
											Cached spot
										</div>
									</div>
									<div class="pd-stat">
										<div class="pd-stat-label">Helius RPC</div>
										<div class="pd-stat-value" id="pd-stat-rpc">—</div>
										<div class="pd-stat-sub" id="pd-stat-rpc-sub">
											Mainnet slot
										</div>
									</div>
									<div class="pd-stat">
										<div class="pd-stat-label">Mints (24h)</div>
										<div class="pd-stat-value" id="pd-stat-mints">—</div>
										<div class="pd-stat-sub">Pump.fun creations</div>
									</div>
									<div class="pd-stat">
										<div class="pd-stat-label">Graduations</div>
										<div class="pd-stat-value" id="pd-stat-grads">—</div>
										<div class="pd-stat-sub">Bonded to AMM</div>
									</div>
								</div>
							</div>
						</div>

						<div class="pd-panel pd-mod-12">
							<div class="pd-panel-head">
								<h2 data-i18n="pump_dashboard.market_chart">Market chart</h2>
								<div class="pd-spacer"></div>
								<select
									class="pd-select"
									id="pd-chart-token"
									aria-label="Select token for the market chart"
									style="max-width: 280px"
								>
									<option value="" disabled selected data-i18n="pump_dashboard.loading_trending_tokens">
										Loading trending tokens…
									</option>
								</select>
								<button
									class="pd-btn pd-btn-sm"
									id="pd-chart-retry"
									type="button"
									hidden
								 data-i18n="pump_dashboard.retry">
									Retry
								</button>
							</div>
							<div class="pd-panel-body">
								<div
									id="pd-chart-meta"
									style="
										display: flex;
										gap: 1rem;
										flex-wrap: wrap;
										align-items: baseline;
										margin-bottom: 0.6rem;
										min-height: 1.2rem;
										font-size: 0.82rem;
										color: var(--ink-dim);
									"
								></div>
								<div id="pd-chart-switch"></div>
								<div id="pd-chart-native" style="position: relative">
									<canvas
										id="pd-market-chart"
										style="width: 100%; height: 300px; display: block"
									></canvas>
									<div
										id="pd-chart-tooltip"
										style="
											position: absolute;
											pointer-events: none;
											display: none;
											background: var(--surface-1);
											border: 1px solid var(--stroke-strong);
											border-radius: 6px;
											padding: 0.35rem 0.55rem;
											font-family: var(--font-mono);
											font-size: 0.72rem;
											color: var(--accent);
											white-space: nowrap;
											z-index: 3;
											transform: translate(-50%, -120%);
										"
									></div>
								</div>
							</div>
						</div>

						<div class="pd-panel pd-mod-6">
							<div class="pd-panel-head">
								<h2 data-i18n-html="pump_dashboard.high_conviction">High conviction <span class="pd-oracle-live-dot" aria-hidden="true"></span></h2>
								<div class="pd-spacer"></div>
								<a class="pd-btn pd-btn-sm" href="/oracle" style="font-size:11px" data-i18n="pump_dashboard.oracle">Oracle →</a>
							</div>
							<div class="pd-oracle-stats-row" id="pd-oracle-stats-row">
								<div class="pd-oracle-stat"><span class="pd-oracle-stat-val" id="pds-agents">—</span><span class="pd-oracle-stat-lbl" data-i18n="pump_dashboard.armed">Armed</span></div>
								<div class="pd-oracle-stat"><span class="pd-oracle-stat-val" id="pds-scored">—</span><span class="pd-oracle-stat-lbl" data-i18n="pump_dashboard.scored_24h">Scored 24h</span></div>
								<div class="pd-oracle-stat"><span class="pd-oracle-stat-val positive" id="pds-winrate">—</span><span class="pd-oracle-stat-lbl" data-i18n="pump_dashboard.win_rate">Win rate</span></div>
								<div class="pd-oracle-stat"><span class="pd-oracle-stat-val" id="pds-open">—</span><span class="pd-oracle-stat-lbl" data-i18n="pump_dashboard.open">Open</span></div>
								<div class="pd-oracle-stat"><span class="pd-oracle-stat-val" id="pds-ath">—</span><span class="pd-oracle-stat-lbl" data-i18n="pump_dashboard.best_ath">Best ATH</span></div>
							</div>
							<div class="pd-panel-body no-pad">
								<div id="pd-oracle-feed" class="pd-oracle-feed">
									<div class="pd-oracle-sk"></div>
									<div class="pd-oracle-sk"></div>
									<div class="pd-oracle-sk"></div>
								</div>
							</div>
						</div>

						<div class="pd-panel pd-mod-6">
							<div class="pd-panel-head">
								<h2 data-i18n="pump_dashboard.live_feed">Live feed</h2>
								<span class="pd-badge" id="pd-activity-count">0</span>
								<div class="pd-spacer"></div>
								<button
									class="pd-btn pd-btn-sm"
									id="pd-clear-dash-feed"
									type="button"
								 data-i18n="pump_dashboard.clear">
									Clear
								</button>
							</div>
							<div class="pd-panel-body no-pad">
								<div
									class="pd-feed"
									id="pd-dashboard-feed"
									style="max-height: 360px"
								>
									<div class="pd-empty">
										<svg
											viewBox="0 0 24 24"
											fill="none"
											stroke="currentColor"
											stroke-width="1.5"
											aria-hidden="true"
										>
											<path d="M3 12c0-5 4-9 9-9" />
											<path d="M3 8c0-3 2.4-5 5-5" />
											<circle
												cx="5"
												cy="19"
												r="1.6"
												fill="currentColor"
												stroke="none"
											/>
										</svg>
										<div>Waiting for the realtime feed…</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</section>

				<!-- ═══════ Live Feed page ═══════ -->
				<section class="pd-page" id="page-feed" aria-label="Live feed">
					<div class="pd-panel">
						<div class="pd-panel-head">
							<h2 data-i18n="pump_dashboard.realtime_feed">Realtime feed</h2>
							<span class="pd-badge" id="pd-feed-count">0</span>
							<div class="pd-spacer"></div>
							<label
								style="
									display: flex;
									align-items: center;
									gap: 0.4rem;
									font-size: 0.78rem;
									color: var(--ink-dim);
								"
							>
								<input type="checkbox" class="pd-toggle" id="pd-feed-pause" /> Pause
							</label>
							<button class="pd-btn pd-btn-sm" id="pd-clear-live-feed" type="button" data-i18n="pump_dashboard.clear_2">
								Clear
							</button>
						</div>
						<div class="pd-filter-row" role="group" aria-label="Filter feed events by type">
							<button class="pd-filter-btn is-active" data-filter="all" type="button" aria-pressed="true" data-i18n="pump_dashboard.all">
								All
							</button>
							<button class="pd-filter-btn" data-filter="launch" type="button" aria-pressed="false" data-i18n="pump_dashboard.launches">
								Launches
							</button>
							<button class="pd-filter-btn" data-filter="trade" type="button" aria-pressed="false" data-i18n="pump_dashboard.trades">
								Trades
							</button>
							<button class="pd-filter-btn" data-filter="whale" type="button" aria-pressed="false" data-i18n="pump_dashboard.whales">
								Whales
							</button>
							<button class="pd-filter-btn" data-filter="graduation" type="button" aria-pressed="false" data-i18n="pump_dashboard.graduations">
								Graduations
							</button>
							<button class="pd-filter-btn" data-filter="claim" type="button" aria-pressed="false" data-i18n="pump_dashboard.claims">
								Claims
							</button>
						</div>
						<div class="pd-panel-body no-pad">
							<div
								class="pd-feed"
								id="pd-live-feed"
								style="max-height: calc(100vh - 280px)"
							>
								<div class="pd-empty">
									<svg
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										stroke-width="1.5"
										aria-hidden="true"
									>
										<path d="M3 12c0-5 4-9 9-9" />
										<path d="M3 8c0-3 2.4-5 5-5" />
										<circle
											cx="5"
											cy="19"
											r="1.6"
											fill="currentColor"
											stroke="none"
										/>
									</svg>
									<div>
										Connecting to
										<span class="pd-mono" data-i18n="pump_dashboard.wss_pumpportal_fun_api_data">wss://pumpportal.fun/api/data</span>…
									</div>
								</div>
							</div>
						</div>
					</div>
				</section>

				<!-- ═══════ Watch List page ═══════ -->
				<section class="pd-page" id="page-watches" aria-label="Watch list">
					<div style="display: flex; gap: 0.5rem; margin-bottom: 1rem">
						<button class="pd-btn is-primary" id="pd-add-watch-btn" type="button" data-i18n="pump_dashboard.add_watch">
							+ Add watch
						</button>
						<button class="pd-btn" id="pd-refresh-watches" type="button" data-i18n="pump_dashboard.refresh">
							Refresh
						</button>
					</div>
					<div class="pd-panel">
						<div class="pd-panel-head">
							<h2 data-i18n="pump_dashboard.active_watches">Active watches</h2>
							<span class="pd-badge" id="pd-watches-count">0</span>
						</div>
						<div class="pd-panel-body no-pad">
							<table class="pd-table">
								<thead>
									<tr>
										<th data-i18n="pump_dashboard.wallet">Wallet</th>
										<th data-i18n="pump_dashboard.label">Label</th>
										<th data-i18n="pump_dashboard.token_filter">Token filter</th>
										<th data-i18n="pump_dashboard.webhook">Webhook</th>
										<th data-i18n="pump_dashboard.created">Created</th>
										<th></th>
									</tr>
								</thead>
								<tbody id="pd-watches-table">
									<tr>
										<td colspan="6" class="pd-empty" data-i18n="pump_dashboard.loading_watches">Loading watches…</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
				</section>

				<!-- ═══════ Claims page ═══════ -->
				<section class="pd-page" id="page-claims" aria-label="Fee claims">
					<div class="pd-form-inline">
						<div class="pd-form-group" style="flex: 2">
							<label for="pd-claims-wallet-filter" data-i18n="pump_dashboard.filter_wallet">Filter wallet</label>
							<input
								class="pd-input"
								type="text"
								id="pd-claims-wallet-filter"
								placeholder="Solana address (optional)…"
							/>
						</div>
						<div class="pd-form-group" style="flex: 1">
							<label for="pd-claims-type-filter" data-i18n="pump_dashboard.type">Type</label>
							<select class="pd-select" id="pd-claims-type-filter">
								<option value="" data-i18n="pump_dashboard.all_types">All types</option>
								<option value="creator_fee" data-i18n="pump_dashboard.creator_fee">Creator fee</option>
								<option value="cashback" data-i18n="pump_dashboard.cashback">Cashback</option>
							</select>
						</div>
						<button class="pd-btn is-primary" id="pd-refresh-claims" type="button" data-i18n="pump_dashboard.search">
							Search
						</button>
					</div>
					<div class="pd-panel">
						<div class="pd-panel-head">
							<h2 data-i18n="pump_dashboard.fee_claims">Fee claims</h2>
							<span class="pd-badge" id="pd-claims-count">0</span>
							<div class="pd-spacer"></div>
							<button class="pd-btn pd-btn-sm" id="pd-export-claims" type="button" data-i18n="pump_dashboard.export_csv">
								Export CSV
							</button>
						</div>
						<div class="pd-panel-body no-pad">
							<table class="pd-table">
								<thead>
									<tr>
										<th data-i18n="pump_dashboard.time">Time</th>
										<th data-i18n="pump_dashboard.wallet_2">Wallet</th>
										<th data-i18n="pump_dashboard.type_2">Type</th>
										<th data-i18n="pump_dashboard.token">Token</th>
										<th data-i18n="pump_dashboard.amount">Amount</th>
										<th data-i18n="pump_dashboard.tx">TX</th>
									</tr>
								</thead>
								<tbody id="pd-claims-table">
									<tr>
										<td colspan="6" class="pd-empty" data-i18n="pump_dashboard.loading_claims">Loading claims…</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
				</section>

				<!-- ═══════ Alerts page ═══════ -->
				<section class="pd-page" id="page-alerts" aria-label="Alerts">
					<div class="pd-alert-grid">
						<div class="pd-panel pd-rule-form-panel">
							<div class="pd-panel-head">
								<h2 id="pd-rule-form-title" data-i18n="pump_dashboard.new_alert_rule">New alert rule</h2>
								<div class="pd-spacer"></div>
								<button class="pd-btn pd-btn-sm" id="pd-rule-cancel" type="button" hidden data-i18n="pump_dashboard.cancel_edit">Cancel edit</button>
							</div>
							<div class="pd-panel-body" id="pd-rule-form">
								<div class="pd-form-group">
									<label for="pd-rule-kind" data-i18n="pump_dashboard.alert_type">Alert type</label>
									<select class="pd-input" id="pd-rule-kind">
										<option value="graduation" data-i18n="pump_dashboard.graduation_amm">Graduation → AMM</option>
										<option value="price_above" data-i18n="pump_dashboard.market_cap_rises_above">Market cap rises above</option>
										<option value="price_below" data-i18n="pump_dashboard.market_cap_falls_below">Market cap falls below</option>
										<option value="whale_buy" data-i18n="pump_dashboard.whale_buy">Whale buy</option>
										<option value="new_mint" data-i18n="pump_dashboard.new_launch_by_agent">New launch by agent</option>
										<option value="launch_match">New launch matching filters</option>
									</select>
									<div class="pd-field-hint" id="pd-rule-kind-hint"></div>
								</div>
								<div class="pd-form-group" id="pd-rule-scope-group" hidden>
									<label for="pd-rule-scope" data-i18n="pump_dashboard.scope">Scope</label>
									<select class="pd-input" id="pd-rule-scope">
										<option value="global" data-i18n="pump_dashboard.all_graduating_tokens">All graduating tokens</option>
										<option value="mint" data-i18n="pump_dashboard.a_specific_token">A specific token</option>
										<option value="agent" data-i18n="pump_dashboard.a_specific_agent_s_tokens">A specific agent’s tokens</option>
									</select>
								</div>
								<div class="pd-form-group" id="pd-rule-mint-group" hidden>
									<label for="pd-rule-mint" data-i18n="pump_dashboard.token_mint">Token mint</label>
									<input class="pd-input" type="text" id="pd-rule-mint" placeholder="Token mint address" autocomplete="off" spellcheck="false" />
								</div>
								<div class="pd-form-group" id="pd-rule-agent-group" hidden>
									<label for="pd-rule-agent" data-i18n="pump_dashboard.agent">Agent</label>
									<select class="pd-input" id="pd-rule-agent">
										<option value="" data-i18n="pump_dashboard.select_an_agent">Select an agent…</option>
									</select>
									<div class="pd-field-hint" id="pd-rule-agent-hint">Fires when this agent launches a coin through three.ws.</div>
								</div>
								<fieldset class="pd-rule-channels pd-rule-launch" id="pd-rule-launch-group" hidden>
									<legend class="pd-rule-channels-title">Launch filters</legend>
									<div class="pd-form-group">
										<label for="pd-rule-lf-name">Name or ticker <span class="pd-muted">(optional)</span></label>
										<input class="pd-input" type="text" id="pd-rule-lf-name" maxlength="120" placeholder="dog|cat or ai*" autocomplete="off" spellcheck="false" />
										<div class="pd-field-hint">Case-insensitive. <code>|</code> separates alternatives, <code>*</code> is a wildcard.</div>
									</div>
									<div class="pd-rule-launch-grid">
										<div class="pd-form-group">
											<label for="pd-rule-lf-mcmin">Min market cap (USD)</label>
											<input class="pd-input" type="number" id="pd-rule-lf-mcmin" min="0" step="100" inputmode="numeric" />
										</div>
										<div class="pd-form-group">
											<label for="pd-rule-lf-mcmax">Max market cap (USD)</label>
											<input class="pd-input" type="number" id="pd-rule-lf-mcmax" min="0" step="100" inputmode="numeric" />
										</div>
										<div class="pd-form-group">
											<label for="pd-rule-lf-safety">Min safety score (0 to 100)</label>
											<input class="pd-input" type="number" id="pd-rule-lf-safety" min="0" max="100" step="1" inputmode="numeric" />
										</div>
										<div class="pd-form-group">
											<label for="pd-rule-lf-grads">Creator's graduated coins, at least</label>
											<input class="pd-input" type="number" id="pd-rule-lf-grads" min="0" step="1" inputmode="numeric" />
										</div>
										<div class="pd-form-group">
											<label for="pd-rule-lf-launches">Creator's earlier launches, at most</label>
											<input class="pd-input" type="number" id="pd-rule-lf-launches" min="0" step="1" inputmode="numeric" />
										</div>
									</div>
									<div class="pd-rule-launch-flags" role="group" aria-labelledby="pd-rule-lf-flags-title">
										<div class="pd-field-hint" id="pd-rule-lf-flags-title">Skip launches flagged as</div>
										<label class="pd-check"><input type="checkbox" data-lf-flag="dev_dumped" /> Dev dumped</label>
										<label class="pd-check"><input type="checkbox" data-lf-flag="bundle_launch" /> Bundled launch</label>
										<label class="pd-check"><input type="checkbox" data-lf-flag="sniped" /> Sniped</label>
										<label class="pd-check"><input type="checkbox" data-lf-flag="single_whale" /> Single whale</label>
										<label class="pd-check"><input type="checkbox" data-lf-flag="low_diversity" /> Low holder diversity</label>
										<label class="pd-check"><input type="checkbox" data-lf-flag="sell_pressure" /> Sell pressure</label>
									</div>
									<label class="pd-check"><input type="checkbox" id="pd-rule-lf-socials" /> Require at least one social link</label>
								</fieldset>
								<div class="pd-form-group" id="pd-rule-threshold-group" hidden>
									<label for="pd-rule-threshold" id="pd-rule-threshold-label" data-i18n="pump_dashboard.threshold">Threshold</label>
									<input class="pd-input" type="number" id="pd-rule-threshold" min="0" step="any" />
									<div class="pd-field-hint" id="pd-rule-threshold-hint"></div>
								</div>
								<div class="pd-form-group">
									<label for="pd-rule-label" data-i18n-html="pump_dashboard.label_optional">Label <span class="pd-muted">(optional)</span></label>
									<input class="pd-input" type="text" id="pd-rule-label" maxlength="80" placeholder="Auto-named if left blank" />
								</div>
								<div class="pd-rule-channels">
									<div class="pd-rule-channels-title">Delivery channels</div>
									<label class="pd-check"><input type="checkbox" id="pd-rule-inapp" checked /> <span data-i18n="pump_dashboard.in_app_notification">In-app notification</span></label>
									<div class="pd-field-hint pd-rule-inapp-hint">Also sent as a push to your devices and to the Telegram or Discord chats you paired, following your <a href="/dashboard/settings">notification preferences</a>.</div>
									<div class="pd-form-group">
										<label for="pd-rule-webhook" data-i18n-html="pump_dashboard.webhook_url_optional">Webhook URL <span class="pd-muted">(optional)</span></label>
										<input class="pd-input" type="url" id="pd-rule-webhook" placeholder="https://your-server.com/pump-alerts" autocomplete="off" spellcheck="false" />
										<div class="pd-field-hint">HTTPS only. Each POST is HMAC-signed with a per-rule secret revealed after you save.</div>
									</div>
									<div class="pd-form-group">
										<label for="pd-rule-telegram" data-i18n-html="pump_dashboard.telegram_chat_id_optional">Telegram chat ID <span class="pd-muted">(optional)</span></label>
										<input class="pd-input" type="text" id="pd-rule-telegram" placeholder="123456789 or @yourchannel" autocomplete="off" spellcheck="false" />
										<div class="pd-field-hint">Message the platform bot first so it can reach you. Numeric chat id or @username.</div>
									</div>
								</div>
								<div class="pd-form-group">
									<label for="pd-rule-cooldown" data-i18n-html="pump_dashboard.cooldown_seconds">Cooldown <span class="pd-muted">(seconds)</span></label>
									<input class="pd-input" type="number" id="pd-rule-cooldown" min="5" max="86400" step="5" value="300" />
									<div class="pd-field-hint">Minimum gap between deliveries for this rule. Prevents alert storms.</div>
								</div>
								<button class="pd-btn is-primary" id="pd-rule-save" type="button" data-i18n="pump_dashboard.create_alert_rule">Create alert rule</button>
								<div class="pd-rule-signin-note" id="pd-rule-signin-note" hidden>
									Sign in to create alerts that fire across devices. <a href="/login" class="pd-link" data-i18n="pump_dashboard.sign_in">Sign in</a>
								</div>
							</div>
						</div>
						<div class="pd-panel pd-rules-list-panel">
							<div class="pd-panel-head">
								<h2 data-i18n="pump_dashboard.your_alert_rules">Your alert rules</h2>
								<div class="pd-spacer"></div>
								<button class="pd-btn pd-btn-sm" id="pd-rules-refresh" type="button" data-i18n="pump_dashboard.refresh_2">Refresh</button>
							</div>
							<div class="pd-panel-body no-pad">
								<div id="pd-rules-list" class="pd-rules-list" aria-live="polite" aria-busy="false">
									<div class="pd-empty">Loading your alert rules…</div>
								</div>
							</div>
						</div>
					</div>
					<div class="pd-panel">
						<div class="pd-panel-head">
							<h2 data-i18n="pump_dashboard.alert_history">Alert history</h2>
							<div class="pd-feed-legend">Live this session + delivered server-side</div>
							<div class="pd-spacer"></div>
							<button class="pd-btn pd-btn-sm" id="pd-clear-alert-feed" type="button" data-i18n="pump_dashboard.clear_3">Clear</button>
						</div>
						<div class="pd-panel-body no-pad">
							<div class="pd-feed" id="pd-alert-feed" style="max-height: 360px">
								<div class="pd-empty">
									<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
										<path d="M5 16c0-4.5 1.5-10 7-10s7 5.5 7 10M3 16h18M10 19h4" />
									</svg>
									<div>No alerts yet — create a rule above and matches will appear here and on every device.</div>
								</div>
							</div>
						</div>
					</div>
				</section>

				<!-- ═══════ Token Scanner page ═══════ -->
				<section class="pd-page" id="page-scanner" aria-label="Token scanner">
					<div class="pd-form-inline">
						<div class="pd-form-group" style="flex: 1">
							<label for="pd-scanner-mint" data-i18n="pump_dashboard.token_mint_address">Token mint address</label>
							<input
								class="pd-input"
								type="text"
								id="pd-scanner-mint"
								placeholder="Enter Solana token mint…"
							/>
						</div>
						<button class="pd-btn is-primary" id="pd-scan-token" type="button" data-i18n="pump_dashboard.scan">
							Scan
						</button>
					</div>
					<div class="pd-inline-status" id="pd-scan-status" role="status" hidden></div>
					<div id="pd-scanner-results" hidden>
						<div class="pd-stat-grid" style="margin-bottom: 1rem">
							<div class="pd-stat">
								<div class="pd-stat-label">Risk score</div>
								<div class="pd-stat-value" id="pd-scan-score">—</div>
							</div>
							<div class="pd-stat">
								<div class="pd-stat-label">Risk level</div>
								<div class="pd-stat-value" id="pd-scan-level">—</div>
							</div>
							<div class="pd-stat">
								<div class="pd-stat-label">Pump.fun token</div>
								<div class="pd-stat-value" id="pd-scan-pump">—</div>
							</div>
							<div class="pd-stat">
								<div class="pd-stat-label">Honeypot risk</div>
								<div class="pd-stat-value" id="pd-scan-honeypot">—</div>
							</div>
						</div>

						<div class="pd-panel">
							<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.security_checks">Security checks</h2></div>
							<div class="pd-panel-body no-pad">
								<table class="pd-table">
									<thead>
										<tr>
											<th data-i18n="pump_dashboard.check">Check</th>
											<th data-i18n="pump_dashboard.status">Status</th>
											<th data-i18n="pump_dashboard.detail">Detail</th>
										</tr>
									</thead>
									<tbody id="pd-scan-checks"></tbody>
								</table>
							</div>
						</div>
					</div>
				</section>

				<!-- ═══════ Quote Engine page ═══════ -->
				<section class="pd-page" id="page-quoting" aria-label="Quote engine">
					<div class="pd-config-grid">
						<div class="pd-panel">
							<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.buy_quote">Buy quote</h2></div>
							<div class="pd-panel-body">
								<div class="pd-form-group">
									<label for="pd-quote-buy-mint" data-i18n="pump_dashboard.token_mint_2">Token mint</label>
									<input
										class="pd-input"
										type="text"
										id="pd-quote-buy-mint"
										placeholder="Token mint address…"
									/>
								</div>
								<div class="pd-form-group">
									<label for="pd-quote-buy-amount" data-i18n="pump_dashboard.sol_amount">SOL amount</label>
									<input
										class="pd-input"
										type="number"
										id="pd-quote-buy-amount"
										value="1"
										min="0.001"
										step="0.001"
									/>
								</div>
								<button
									class="pd-btn is-primary"
									id="pd-get-buy-quote"
									type="button"
								 data-i18n="pump_dashboard.get_buy_quote">
									Get buy quote
								</button>
								<div id="pd-quote-buy-result" style="margin-top: 0.85rem"></div>
							</div>
						</div>

						<div class="pd-panel">
							<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.sell_quote">Sell quote</h2></div>
							<div class="pd-panel-body">
								<div class="pd-form-group">
									<label for="pd-quote-sell-mint" data-i18n="pump_dashboard.token_mint_3">Token mint</label>
									<input
										class="pd-input"
										type="text"
										id="pd-quote-sell-mint"
										placeholder="Token mint address…"
									/>
								</div>
								<div class="pd-form-group">
									<label for="pd-quote-sell-amount" data-i18n="pump_dashboard.token_amount">Token amount</label>
									<input
										class="pd-input"
										type="number"
										id="pd-quote-sell-amount"
										value="1000000"
										min="1"
										step="1"
									/>
								</div>
								<button
									class="pd-btn is-primary"
									id="pd-get-sell-quote"
									type="button"
								 data-i18n="pump_dashboard.get_sell_quote">
									Get sell quote
								</button>
								<div id="pd-quote-sell-result" style="margin-top: 0.85rem"></div>
							</div>
						</div>
					</div>
				</section>

				<!-- ═══════ Vanity Generator page ═══════ -->
				<section class="pd-page" id="page-vanity" aria-label="Vanity generator">
					<div class="pd-panel">
						<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.vanity_address_generator">Vanity address generator</h2></div>
						<div class="pd-panel-body">
							<div class="pd-callout" style="margin-bottom: 1rem">
								Grinds Ed25519 keypairs locally in Web Workers. The secret key never
								leaves your browser. For a fuller UI with worker tuning, use
								<a href="/vanity-wallet" data-i18n="pump_dashboard.vanity_wallet">/vanity-wallet</a>.
							</div>
							<div class="pd-form-row">
								<div class="pd-form-group">
									<label for="pd-vanity-prefix" data-i18n="pump_dashboard.prefix_optional">Prefix (optional)</label>
									<input
										class="pd-input"
										type="text"
										id="pd-vanity-prefix"
										placeholder="e.g. pump"
										maxlength="6"
									/>
								</div>
								<div class="pd-form-group">
									<label for="pd-vanity-suffix" data-i18n="pump_dashboard.suffix_optional">Suffix (optional)</label>
									<input
										class="pd-input"
										type="text"
										id="pd-vanity-suffix"
										placeholder="e.g. fun"
										maxlength="6"
									/>
								</div>
							</div>
							<div style="display: flex; gap: 0.5rem">
								<button
									class="pd-btn is-primary"
									id="pd-vanity-start"
									type="button"
								 data-i18n="pump_dashboard.generate">
									Generate
								</button>
								<button
									class="pd-btn is-danger"
									id="pd-vanity-stop"
									type="button"
									hidden
								 data-i18n="pump_dashboard.stop">
									Stop
								</button>
							</div>
							<div
								id="pd-vanity-status"
								style="
									margin-top: 0.85rem;
									font-size: 0.82rem;
									color: var(--ink-dim);
									font-family: var(--font-mono);
								"
							></div>
							<div id="pd-vanity-result" style="margin-top: 0.85rem"></div>
						</div>
					</div>
				</section>

				<!-- ═══════ Default Agent page ═══════ -->
				<section class="pd-page" id="page-animations" aria-label="Default agent">
					<div class="pd-panel">
						<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.default_agent">Default agent</h2></div>
						<div class="pd-panel-body">
							<div class="pd-config-grid">
								<div
									id="pd-agent-view-container"
									style="
										background: #000;
										border: 1px solid var(--stroke);
										min-height: 320px;
										display: flex;
										align-items: center;
										justify-content: center;
										border-radius: var(--radius-md);
										overflow: hidden;
									"
								>
									<iframe
										id="pd-agent-iframe"
										style="width: 100%; height: 100%; border: none"
										title="Default agent preview"
									></iframe>
								</div>
								<div>
									<div class="pd-form-group">
										<label for="pd-speech-input" data-i18n="pump_dashboard.speech">Speech</label>
										<input
											class="pd-input"
											type="text"
											id="pd-speech-input"
											placeholder="Enter text to speak…"
										/>
										<div style="display: flex; gap: 0.4rem; margin-top: 0.5rem">
											<button
												class="pd-btn is-primary"
												id="pd-speak-btn"
												type="button"
											 data-i18n="pump_dashboard.speak">
												Speak
											</button>
											<button
												class="pd-btn is-danger"
												id="pd-speak-stop"
												type="button"
												hidden
											 data-i18n="pump_dashboard.stop_2">
												Stop
											</button>
										</div>
									</div>
									<div class="pd-form-group">
										<div class="pd-form-label" id="pd-quick-actions-label" data-i18n="pump_dashboard.quick_actions">Quick actions</div>
										<div style="display: flex; gap: 0.4rem; flex-wrap: wrap" role="group" aria-labelledby="pd-quick-actions-label">
											<button
												class="pd-btn"
												data-agent-action="emote"
												type="button"
											 data-i18n="pump_dashboard.emote">
												Emote
											</button>
											<button
												class="pd-btn"
												data-agent-action="wave"
												type="button"
											 data-i18n="pump_dashboard.wave">
												Wave
											</button>
											<button
												class="pd-btn"
												data-agent-action="verify"
												type="button"
											 data-i18n="pump_dashboard.verify_model">
												Verify model
											</button>
										</div>
									</div>
									<div class="pd-form-group">
										<label for="pd-anim-select" data-i18n="pump_dashboard.animation">Animation</label>
										<select class="pd-select" id="pd-anim-select">
											<option data-i18n="pump_dashboard.idle">Idle</option>
											<option data-i18n="pump_dashboard.walk">Walk</option>
											<option data-i18n="pump_dashboard.run">Run</option>
											<option data-i18n="pump_dashboard.dance">Dance</option>
										</select>
										<button
											class="pd-btn is-primary"
											id="pd-play-anim"
											type="button"
											style="margin-top: 0.5rem"
										 data-i18n="pump_dashboard.play">
											Play
										</button>
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="pd-panel">
						<div class="pd-panel-head">
							<h2 data-i18n="pump_dashboard.your_agents">Your agents</h2>
							<div class="pd-spacer"></div>
							<a class="pd-btn is-primary pd-btn-sm" href="/create" data-i18n="pump_dashboard.new_agent">+ New agent</a>
						</div>
						<div class="pd-panel-body no-pad">
							<table class="pd-table">
								<thead>
									<tr>
										<th data-i18n="pump_dashboard.name">Name</th>
										<th data-i18n="pump_dashboard.description">Description</th>
										<th data-i18n="pump_dashboard.created_2">Created</th>
										<th></th>
									</tr>
								</thead>
								<tbody id="pd-custom-agents-table">
									<tr>
										<td colspan="4" class="pd-empty" data-i18n="pump_dashboard.loading">Loading…</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
				</section>

				<!-- ═══════ Config page ═══════ -->
				<section class="pd-page" id="page-config" aria-label="Configuration">
					<div class="pd-callout" style="margin-bottom: 1rem">
						This page lets you point the dashboard at an external
						<a href="https://github.com/nirholas/pumpkit" target="_blank" rel="noopener"
							 data-i18n="pump_dashboard.pumpkit_style">PumpKit-style</a
						>
						backend for advanced features like watches and fee claim ingestion. By
						default, the dashboard uses the three.ws-hosted
						<span class="pd-mono" data-i18n="pump_dashboard.api_pump">/api/pump/*</span> endpoints, which power the Live
						Feed, network health, quotes, and the token scanner without any setup.
					</div>
					<div class="pd-config-grid">
						<div class="pd-panel">
							<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.connection">Connection</h2></div>
							<div class="pd-panel-body">
								<div class="pd-form-group">
									<label for="pd-cfg-api-url"
										 data-i18n-html="pump_dashboard.api_base_url">API base URL
										<span class="pd-probe" id="pd-probe-api"></span
									></label>
									<input
										class="pd-input"
										type="text"
										id="pd-cfg-api-url"
										placeholder="https://your-pumpkit.example"
									/>
								</div>
								<div class="pd-form-group">
									<label for="pd-cfg-ws-url"
										 data-i18n-html="pump_dashboard.websocket_url">WebSocket URL
										<span class="pd-probe" id="pd-probe-ws"></span
									></label>
									<input class="pd-input" type="text" id="pd-cfg-ws-url" />
								</div>
								<div class="pd-form-group">
									<label for="pd-cfg-api-key"
										 data-i18n-html="pump_dashboard.api_key">API key <span class="pd-probe" id="pd-probe-key"></span
									></label>
									<input
										class="pd-input"
										type="password"
										id="pd-cfg-api-key"
										placeholder="Optional API key…"
									/>
								</div>
								<button class="pd-btn is-primary" id="pd-save-config" type="button" data-i18n="pump_dashboard.save_reconnect">
									Save &amp; reconnect
								</button>
							</div>
						</div>

						<div class="pd-panel">
							<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.solana_rpc">Solana RPC</h2></div>
							<div class="pd-panel-body">
								<div class="pd-form-group">
									<label for="pd-cfg-rpc-url"
										 data-i18n-html="pump_dashboard.rpc_endpoint">RPC endpoint
										<span class="pd-probe" id="pd-probe-rpc"></span
									></label>
									<input
										class="pd-input"
										type="text"
										id="pd-cfg-rpc-url"
										value="/api/solana-rpc"
										placeholder="/api/solana-rpc or your own RPC URL"
									/>
								</div>
								<div class="pd-form-group">
									<label for="pd-cfg-commitment" data-i18n="pump_dashboard.commitment_level">Commitment level</label>
									<select class="pd-select" id="pd-cfg-commitment">
										<option value="confirmed" selected data-i18n="pump_dashboard.confirmed">Confirmed</option>
										<option value="finalized" data-i18n="pump_dashboard.finalized">Finalized</option>
										<option value="processed" data-i18n="pump_dashboard.processed">Processed</option>
									</select>
								</div>
							</div>
						</div>
					</div>
				</section>

				<!-- ═══════ API page ═══════ -->
				<section class="pd-page" id="page-api" aria-label="API reference">
					<div class="pd-panel" style="margin-bottom: 1rem">
						<div class="pd-panel-head">
							<h2 data-i18n="pump_dashboard.your_keys">Your keys</h2>
							<div class="pd-spacer"></div>
							<span class="pd-badge" id="pd-keys-count">—</span>
						</div>
						<div class="pd-panel-body">
							<form
								id="pd-key-create-form"
								style="
									display: flex;
									gap: 0.75rem;
									flex-wrap: wrap;
									align-items: flex-end;
									margin-bottom: 1rem;
								"
							>
								<div
									class="pd-form-group"
									style="flex: 2; min-width: 200px; margin: 0"
								>
									<label for="pd-key-name" data-i18n="pump_dashboard.key_name">Key name</label>
									<input
										class="pd-input"
										type="text"
										id="pd-key-name"
										maxlength="80"
										placeholder="e.g. CI pipeline"
										required
									/>
								</div>
								<div
									class="pd-form-group"
									style="flex: 1; min-width: 160px; margin: 0"
								>
									<label for="pd-key-expiry" data-i18n="pump_dashboard.expires_optional">Expires (optional)</label>
									<input
										class="pd-input"
										type="datetime-local"
										id="pd-key-expiry"
									/>
								</div>
								<div
									class="pd-form-group"
									style="flex: 2; min-width: 240px; margin: 0"
								>
									<div class="pd-form-label" id="pd-key-scopes-label" data-i18n="pump_dashboard.scopes">Scopes</div>
									<div
										role="group"
										aria-labelledby="pd-key-scopes-label"
										style="
											display: flex;
											gap: 0.85rem;
											flex-wrap: wrap;
											font-size: 0.82rem;
											color: var(--ink-dim);
										"
									>
										<label
											style="display: flex; gap: 0.3rem; align-items: center"
											><input
												type="checkbox"
												class="pd-key-scope"
												value="avatars:read"
												checked
											/>
											avatars:read</label
										>
										<label
											style="display: flex; gap: 0.3rem; align-items: center"
											><input
												type="checkbox"
												class="pd-key-scope"
												value="avatars:write"
												checked
											/>
											avatars:write</label
										>
										<label
											style="display: flex; gap: 0.3rem; align-items: center"
											><input
												type="checkbox"
												class="pd-key-scope"
												value="avatars:delete"
											/>
											avatars:delete</label
										>
										<label
											style="display: flex; gap: 0.3rem; align-items: center"
											><input
												type="checkbox"
												class="pd-key-scope"
												value="profile"
											/>
											profile</label
										>
									</div>
								</div>
								<button class="pd-btn is-primary" id="pd-key-create" type="submit" data-i18n="pump_dashboard.create_key">
									Create key
								</button>
							</form>
							<table class="pd-table">
								<thead>
									<tr>
										<th data-i18n="pump_dashboard.name_2">Name</th>
										<th data-i18n="pump_dashboard.prefix">Prefix</th>
										<th data-i18n="pump_dashboard.scopes_2">Scopes</th>
										<th data-i18n="pump_dashboard.created_3">Created</th>
										<th data-i18n="pump_dashboard.last_used">Last used</th>
										<th data-i18n="pump_dashboard.expires">Expires</th>
										<th></th>
									</tr>
								</thead>
								<tbody id="pd-keys-table">
									<tr>
										<td colspan="7" class="pd-empty" data-i18n="pump_dashboard.open_the_api_tab_to_load_your">
											Open the API tab to load your keys.
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
					<div class="pd-panel">
						<div class="pd-panel-head"><h2 data-i18n="pump_dashboard.api_endpoints">API endpoints</h2></div>
						<div class="pd-panel-body">
							<p
								style="
									color: var(--ink-dim);
									font-size: 0.88rem;
									margin-bottom: 1rem;
								"
							 data-i18n-html="pump_dashboard.three_ws_ships_these_pump_endpoints_for">
								three.ws ships these Pump endpoints for free, no auth required.
								Resolved against:
								<span class="pd-mono-inline" id="pd-api-endpoint-display">—</span>
							</p>
							<table class="pd-table">
								<thead>
									<tr>
										<th data-i18n="pump_dashboard.method">Method</th>
										<th data-i18n="pump_dashboard.path">Path</th>
										<th data-i18n="pump_dashboard.description_2">Description</th>
										<th data-i18n="pump_dashboard.auth">Auth</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td data-i18n-html="pump_dashboard.get"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_healthz">/api/healthz</td>
										<td data-i18n="pump_dashboard.health_check">Health check</td>
										<td data-i18n="pump_dashboard.no">No</td>
									</tr>
									<tr>
										<td data-i18n-html="pump_dashboard.get_2"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_pump_helius_stats">/api/pump/helius-stats</td>
										<td data-i18n="pump_dashboard.sol_price_network_slot_feed_counts">SOL price, network slot, feed counts</td>
										<td data-i18n="pump_dashboard.no_2">No</td>
									</tr>
									<tr>
										<td data-i18n-html="pump_dashboard.get_3"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_pump_channel_feed">/api/pump/channel-feed</td>
										<td data-i18n="pump_dashboard.recent_mints_whales_claims_paginated">Recent mints, whales, claims (paginated)</td>
										<td data-i18n="pump_dashboard.no_3">No</td>
									</tr>
									<tr>
										<td data-i18n-html="pump_dashboard.get_4"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_pump_trades_stream">/api/pump/trades-stream</td>
										<td data-i18n="pump_dashboard.sse_live_trade_stream_pumpportal_proxy">SSE live trade stream (PumpPortal proxy)</td>
										<td data-i18n="pump_dashboard.no_4">No</td>
									</tr>
									<tr>
										<td data-i18n-html="pump_dashboard.get_5"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_pump_curve_mint">/api/pump/curve?mint=…</td>
										<td data-i18n="pump_dashboard.bonding_curve_spot_price_graduation_progress">Bonding curve, spot price, graduation progress</td>
										<td data-i18n="pump_dashboard.no_5">No</td>
									</tr>
									<tr>
										<td data-i18n-html="pump_dashboard.get_6"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_pump_quote_sdk_mint_side_buy">
											/api/pump/quote-sdk?mint=…&amp;side=buy|sell&amp;amount=…
										</td>
										<td data-i18n="pump_dashboard.buy_sell_quote_with_price_impact">Buy/sell quote with price impact</td>
										<td data-i18n="pump_dashboard.no_6">No</td>
									</tr>
									<tr>
										<td data-i18n-html="pump_dashboard.get_7"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_pump_balances">/api/pump/balances</td>
										<td data-i18n="pump_dashboard.sol_token_balances_for_the_signed_in">SOL + token balances for the signed-in wallet</td>
										<td data-i18n="pump_dashboard.session">Session</td>
									</tr>
									<tr>
										<td data-i18n-html="pump_dashboard.get_8"><span class="pd-tag is-buy">GET</span></td>
										<td class="pd-mono" data-i18n="pump_dashboard.api_agents_pumpfun_op_claims">/api/agents/pumpfun?op=claims</td>
										<td data-i18n="pump_dashboard.recent_fee_claim_feed">Recent fee claim feed</td>
										<td data-i18n="pump_dashboard.session_2">Session</td>
									</tr>
								</tbody>
							</table>
							<p
								style="
									color: var(--ink-dim);
									font-size: 0.82rem;
									margin-top: 0.85rem;
								"
							 data-i18n-html="pump_dashboard.for_an_openapi_spec_see_openapi_json">
								For an OpenAPI spec, see <a href="/openapi.json">/openapi.json</a>.
							</p>
						</div>
					</div>
				</section>
			</main>
		</div>

		<!-- ── Add Watch Modal ────────────────── -->
		<div
			class="pd-modal-backdrop"
			id="pd-add-watch-modal"
			role="dialog"
			aria-modal="true"
			aria-labelledby="pd-add-watch-title"
		>
			<div class="pd-modal">
				<h3 id="pd-add-watch-title" data-i18n="pump_dashboard.add_watch_2">Add watch</h3>
				<div class="pd-form-group">
					<label for="pd-watch-wallet" data-i18n="pump_dashboard.wallet_address">Wallet address *</label>
					<input
						class="pd-input"
						type="text"
						id="pd-watch-wallet"
						placeholder="Solana wallet address…"
					/>
				</div>
				<div class="pd-form-group">
					<label for="pd-watch-label" data-i18n="pump_dashboard.label_2">Label</label>
					<input
						class="pd-input"
						type="text"
						id="pd-watch-label"
						placeholder="Optional label…"
					/>
				</div>
				<div class="pd-form-group">
					<label for="pd-watch-token-filter" data-i18n="pump_dashboard.token_filter_comma_separated_mints">Token filter (comma-separated mints)</label>
					<input
						class="pd-input"
						type="text"
						id="pd-watch-token-filter"
						placeholder="Leave empty for all tokens"
					/>
				</div>
				<div class="pd-form-group">
					<label for="pd-watch-webhook" data-i18n="pump_dashboard.webhook_url">Webhook URL</label>
					<input
						class="pd-input"
						type="text"
						id="pd-watch-webhook"
						placeholder="https://your-server.com/webhook"
					/>
				</div>
				<div class="pd-modal-actions">
					<button class="pd-btn" id="pd-cancel-watch" type="button" data-i18n="pump_dashboard.cancel">Cancel</button>
					<button class="pd-btn is-primary" id="pd-create-watch" type="button" data-i18n="pump_dashboard.create_watch">
						Create watch
					</button>
				</div>
			</div>
		</div>

		<!-- ── API key created modal (shows plaintext token once) ────────────── -->
		<div
			class="pd-modal-backdrop"
			id="pd-key-modal"
			role="dialog"
			aria-modal="true"
			aria-labelledby="pd-key-modal-title"
		>
			<div class="pd-modal">
				<h3 id="pd-key-modal-title" data-i18n="pump_dashboard.api_key_created">API key created</h3>
				<p style="font-size: 0.85rem; color: var(--warn); margin: 0 0 0.75rem" data-i18n="pump_dashboard.copy_this_token_now_you_won_t">
					Copy this token now — you won't be able to see it again.
				</p>
				<div class="pd-form-group">
					<label for="pd-key-token" data-i18n="pump_dashboard.token_2">Token</label>
					<input class="pd-input pd-mono" type="text" id="pd-key-token" readonly />
				</div>
				<div class="pd-modal-actions">
					<button class="pd-btn" id="pd-key-copy" type="button" data-i18n="pump_dashboard.copy">Copy</button>
					<button class="pd-btn is-primary" id="pd-key-done" type="button" data-i18n="pump_dashboard.done">Done</button>
				</div>
			</div>
		</div>

		<div class="pd-toast-container" id="pd-toasts" role="status" aria-live="polite"></div>

		<script type="module">
			// ═════════════════════════════════════════════════════════════════
			//  Pump Dashboard — site-cohesive rewrite.
			//  Defaults to the three.ws-hosted /api/pump/* endpoints for the
			//  Live Feed, network health, quotes, and the token scanner.
			//  Pointing the API URL in Config at a PumpKit deployment unlocks
			//  the optional Watches + per-wallet CRUD endpoints.
			// ═════════════════════════════════════════════════════════════════

			import { grindVanity } from '/src/solana/vanity/grinder.js';
			import { validatePattern } from '/src/solana/vanity/validation.js';
			import {
				initWalletButton,
				getConnectedWallet,
				getConnectedWalletAddress,
			} from '/src/wallet.js';
			import { emptyStateHTML } from '/src/shared/state-kit.js';
			import { mountSwitchableChart } from '/src/shared/chart-switcher.js';

			// Some embedded webviews — notably the in-app browsers X/Twitter
			// and a few Android wrappers ship — expose `window.localStorage`
			// as `null`, or throw on access in private mode. Reading it
			// directly during module init crashed the whole page. Route every
			// storage call through this shim: it probes the real store once,
			// and silently degrades to an in-memory map when it's unavailable
			// so the dashboard still loads (config just won't persist).
			const safeStorage = (() => {
				let store = null;
				try {
					store = window.localStorage;
					const probe = '__twx_probe__';
					store.setItem(probe, '1');
					store.removeItem(probe);
				} catch {
					store = null;
				}
				const mem = new Map();
				return {
					getItem(key) {
						if (store) {
							try {
								return store.getItem(key);
							} catch {
								/* fall through to in-memory */
							}
						}
						return mem.has(key) ? mem.get(key) : null;
					},
					setItem(key, value) {
						const v = String(value);
						if (store) {
							try {
								store.setItem(key, v);
								return;
							} catch {
								/* fall through to in-memory */
							}
						}
						mem.set(key, v);
					},
					removeItem(key) {
						if (store) {
							try {
								store.removeItem(key);
								return;
							} catch {
								/* fall through to in-memory */
							}
						}
						mem.delete(key);
					},
				};
			})();

			const PAGE_TITLES = {
				dashboard: 'Dashboard',
				feed: 'Live Feed',
				watches: 'Watch List',
				claims: 'Fee Claims',
				alerts: 'Alerts',
				scanner: 'Token Scanner',
				quoting: 'Quote Engine',
				vanity: 'Vanity Generator',
				animations: 'Default Agent',
				config: 'Configuration',
				api: 'API Reference',
			};

			const state = {
				apiUrl: safeStorage.getItem('pumpbot-api-url') || location.origin,
				wsUrl: safeStorage.getItem('pumpbot-ws-url') || 'wss://pumpportal.fun/api/data',
				apiKey: safeStorage.getItem('pumpbot-api-key') || '',
				// Default to the same-origin proxy (/api/solana-rpc), which forwards
				// to a keyed Helius upstream server-side. The public RPC 403s
				// browser requests, so we also migrate anyone whose stored value is
				// that old broken default onto the proxy; genuine custom RPCs are
				// preserved untouched.
				rpcUrl: (() => {
					const stored = safeStorage.getItem('pumpbot-rpc-url');
					return stored && stored !== 'https://api.mainnet-beta.solana.com'
						? stored
						: '/api/solana-rpc';
				})(),
				currentPage: 'dashboard',
				currentFilter: 'all',
				// null until refreshWatches() has established whether the configured
				// API exposes the PumpKit /api/v1/watches surface.
				watchesSupported: null,
				ws: null,
				feedItems: [],
				feedCount: 0,
				activityCount: 0,
				feedPaused: false,
				alertRules: (() => {
					const v = safeParseJson(safeStorage.getItem('pumpbot-alerts') || '[]', []);
					return Array.isArray(v) ? v : [];
				})(),
				// Deep-link target: /pump-dashboard?agent=<id> (e.g. straight from the
				// launch-token modal) focuses the control panel on that specific agent
				// instead of falling back to the account default.
				agentId: new URLSearchParams(location.search).get('agent') || null,
				vanityAbort: null,
				healthInterval: null,
				networkInterval: null,
				monitorInterval: null,
				walletAddress: null,
				solPrice: null,
				startupAt: Date.now(),
			};

			function safeParseJson(s, fallback) {
				try {
					return JSON.parse(s);
				} catch {
					return fallback;
				}
			}

			function $(id) {
				return document.getElementById(id);
			}

			function escapeHtml(s) {
				return String(s).replace(
					/[&<>"']/g,
					(c) =>
						({
							'&': '&amp;',
							'<': '&lt;',
							'>': '&gt;',
							'"': '&quot;',
							"'": '&#39;',
						})[c],
				);
			}

			function shortAddr(addr) {
				if (!addr) return '';
				const a = String(addr);
				if (a.length <= 12) return a;
				return `${a.slice(0, 4)}…${a.slice(-4)}`;
			}

			// ── Toasts ───────────────────────────────────────────────────

			function toast(message, kind = 'info') {
				const host = $('pd-toasts');
				if (!host) return;
				const div = document.createElement('div');
				div.className = `pd-toast is-${kind}`;
				div.textContent = message;
				host.appendChild(div);
				setTimeout(() => {
					div.style.opacity = '0';
					div.style.transform = 'translateX(8px)';
				}, 3500);
				setTimeout(() => div.remove(), 4000);
			}

			// ── API fetch helper ─────────────────────────────────────────

			async function apiFetch(path, options = {}) {
				const base = path.startsWith('http') ? '' : state.apiUrl;
				const url = base + path;
				const headers = { ...(options.headers || {}) };
				if (state.apiKey) headers['X-API-Key'] = state.apiKey;
				return fetch(url, { credentials: 'include', ...options, headers });
			}

			// ── Navigation ───────────────────────────────────────────────

			// All on-chain JSON-RPC POSTs go through here so failures are surfaced
			// (logged + reflected in the network panel's RPC line) instead of being
			// silently swallowed at each call site. Throws on transport/HTTP/RPC
			// errors so callers can decide how to recover.
			let _rpcErrorClearTimer = null;
			function markRpcError(detail) {
				const sub = $('pd-stat-rpc-sub');
				if (sub) {
					sub.textContent = 'RPC error · ' + detail;
					sub.classList.add('is-danger');
				}
				const dot = $('pd-sol-dot');
				if (dot) dot.className = 'pd-dot is-err';
				// The next network-stats refresh rewrites this line; clear the error
				// styling after a beat in case that refresh is also down so the panel
				// doesn't get stuck red.
				if (_rpcErrorClearTimer) clearTimeout(_rpcErrorClearTimer);
				_rpcErrorClearTimer = setTimeout(() => {
					if (sub) sub.classList.remove('is-danger');
				}, 8000);
			}
			function markRpcOk() {
				const sub = $('pd-stat-rpc-sub');
				if (sub) sub.classList.remove('is-danger');
			}

			// Some Solana providers accept a request and then never answer it
			// (getTokenLargestAccounts is a known offender). Without a bound, the
			// caller's await never settles: the token scanner sat on a click with no
			// result, no error and no way to retry. Time every call out instead.
			const RPC_TIMEOUT_MS = 25000;

			async function rpcCall(rpcBody, { id = 1 } = {}) {
				let resp;
				try {
					resp = await fetch(state.rpcUrl, {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({ jsonrpc: '2.0', id, ...rpcBody }),
						signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
					});
				} catch (e) {
					const timedOut = e?.name === 'TimeoutError' || e?.name === 'AbortError';
					console.warn('[pump-dashboard] RPC transport error:', e?.message || e);
					markRpcError(timedOut ? 'timed out' : 'unreachable');
					throw new Error(
						timedOut
							? 'the Solana RPC did not respond in time'
							: 'the Solana RPC is unreachable',
					);
				}
				if (!resp.ok) {
					console.warn('[pump-dashboard] RPC HTTP', resp.status, 'from', state.rpcUrl);
					markRpcError('HTTP ' + resp.status);
					throw new Error('RPC HTTP ' + resp.status);
				}
				let data;
				try {
					data = await resp.json();
				} catch {
					markRpcError('bad response');
					throw new Error('RPC returned non-JSON');
				}
				if (data && data.error) {
					const msg = data.error.message || 'RPC error';
					console.warn('[pump-dashboard] RPC error:', msg);
					markRpcError(String(msg).slice(0, 40));
					throw new Error(msg);
				}
				markRpcOk();
				return data;
			}

			function navigateTo(page) {
				state.currentPage = page;
				// Keep the URL shareable: every cockpit page is deep-linkable via its #hash.
				if (location.hash.slice(1) !== page) history.replaceState(null, '', '#' + page);
				document
					.querySelectorAll('.pd-page')
					.forEach((p) => p.classList.remove('is-active'));
				const target = $('page-' + page);
				if (target) target.classList.add('is-active');
				document.querySelectorAll('.pd-sidebar nav a').forEach((a) => {
					a.classList.toggle('is-active', a.dataset.page === page);
				});
				$('pd-page-title').textContent = PAGE_TITLES[page] || page;

				if (page === 'animations') loadAgent();
				if (page === 'watches') refreshWatches();
				if (page === 'claims') refreshClaims();
				if (page === 'api') loadApiKeys();
				if (page === 'alerts') loadAlertConfig();
				if (page === 'dashboard') {
					loadFeaturedAgent();
					loadTrendingTokens();
					pollMonitorStats();
				}
			}

			// ── API health + network ─────────────────────────────────────

			async function connectApi() {
				clearInterval(state.healthInterval);
				updateApiStatus('connecting');
				try {
					const resp = await apiFetch('/api/healthz');
					if (resp.ok) {
						updateApiStatus('connected');
						state.healthInterval = setInterval(pollHealth, 15000);
					} else {
						updateApiStatus('error');
					}
				} catch {
					updateApiStatus('error');
					setTimeout(connectApi, 5000);
				}
			}

			async function pollHealth() {
				try {
					const resp = await apiFetch('/api/healthz');
					updateApiStatus(resp.ok ? 'connected' : 'error');
				} catch {
					updateApiStatus('error');
				}
			}

			function updateApiStatus(status) {
				const dot = $('pd-api-dot');
				const label = $('pd-api-status');
				dot.className =
					'pd-dot ' +
					(status === 'connected' ? 'is-on' : status === 'error' ? 'is-err' : 'is-warm');
				label.textContent =
					status === 'connected'
						? 'API: connected'
						: status === 'error'
							? 'API: disconnected'
							: 'API: connecting…';
			}

			async function refreshNetworkStats() {
				try {
					const r = await fetch('/api/pump/helius-stats');
					if (!r.ok) return;
					const data = await r.json();

					const sol = Number(data.sol_price || 0);
					if (sol > 0) {
						state.solPrice = sol;
						$('pd-stat-sol').textContent = '$' + sol.toFixed(2);
						$('pd-sol-status').textContent = 'SOL: $' + sol.toFixed(2);
						$('pd-sol-dot').className = 'pd-dot is-on';
					}

					const h = data.helius || {};
					if (h.enabled) {
						$('pd-stat-rpc').textContent = h.slot
							? Number(h.slot).toLocaleString()
							: 'On';
						$('pd-stat-rpc').classList.add('is-success');
						$('pd-stat-rpc-sub').textContent =
							(h.network || 'mainnet') +
							' · ' +
							(h.blockTime
								? new Date(h.blockTime * 1000).toLocaleTimeString()
								: 'live');
						$('pd-network-badge').textContent = 'Helius live';
					} else {
						$('pd-stat-rpc').textContent = 'Public RPC';
						$('pd-stat-rpc-sub').textContent = 'Helius disabled';
						$('pd-network-badge').textContent = 'Public RPC';
					}

					const f = data.feed || {};
					$('pd-stat-mints').textContent = Number(f.mints || 0).toLocaleString();
					$('pd-stat-grads').textContent = Number(f.graduations || 0).toLocaleString();
				} catch {
					/* network panel is best-effort */
				}
			}

			// ── Featured agent ───────────────────────────────────────────

			function initialsOf(name) {
				const words = String(name || '')
					.trim()
					.split(/\s+/)
					.filter(Boolean);
				if (!words.length) return '?';
				if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
				return (words[0][0] + words[words.length - 1][0]).toUpperCase();
			}

			// Initials tile rendered locally — used as the no-avatar default and as
			// the onerror fallback when a remote avatar_url 404s or times out.
			function featuredInitialsTile(name) {
				return `<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-size:2.2rem;font-weight:700;color:var(--accent);background:linear-gradient(135deg,var(--surface-1),#161616)">${escapeHtml(initialsOf(name))}</div>`;
			}

			function renderFeaturedAvatar(agent) {
				const slot = $('pd-featured-avatar');
				if (!slot) return;
				if (agent.avatar_url) {
					slot.innerHTML = `<img alt="${escapeHtml(agent.display_name || 'Agent')} avatar" style="width:100%;height:100%;object-fit:cover" loading="lazy" />`;
					const img = slot.querySelector('img');
					// Swap to the local initials tile if the remote avatar fails to
					// load — never leave a broken-image icon in the card.
					img.addEventListener('error', () => {
						slot.innerHTML = featuredInitialsTile(agent.display_name);
					});
					img.src = agent.avatar_url;
				} else {
					// Never a stock placeholder — render the agent's initials.
					slot.innerHTML = featuredInitialsTile(agent.display_name);
				}
			}

			// Task 01: the Featured agent is selected platform-wide from real data
			// (top 30-day revenue, else newest public agent) by GET /api/agents/featured.
			async function loadFeaturedAgent() {
				const nameEl = $('pd-featured-name');
				const descEl = $('pd-featured-desc');
				const linkEl = $('pd-featured-link');
				const statsEl = $('pd-featured-stats');
				if (!nameEl) return;
				nameEl.textContent = 'Loading agent…';
				descEl.textContent = 'Fetching the featured agent for the platform.';
				try {
					const resp = await apiFetch('/api/agents/featured');
					if (resp.status === 404) {
						nameEl.textContent = 'No agents available yet';
						descEl.textContent =
							'Be the first — create a 3D agent and it can be featured here.';
						linkEl.onclick = null;
						linkEl.textContent = 'Create agent';
						linkEl.href = '/create';
						if (statsEl) statsEl.hidden = true;
						$('pd-featured-avatar').innerHTML =
							`<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:var(--ink-dim);font-size:0.8rem">No agents yet</div>`;
						return;
					}
					if (!resp.ok) throw new Error('featured ' + resp.status);
					const { data: agent } = await resp.json();
					nameEl.textContent = agent.display_name || 'Untitled agent';
					descEl.textContent = agent.bio || 'A featured 3D agent on three.ws.';
					linkEl.onclick = null;
					linkEl.textContent = 'View profile';
					linkEl.href = agent.detail_url || '/agents/' + agent.id;
					if (statsEl) {
						statsEl.hidden = false;
						statsEl.innerHTML = [
							`<span class="pd-featured-stat"><span class="pd-featured-stat-label">ID</span>${shortAddr(agent.id)}</span>`,
							agent.net_30d > 0
								? `<span class="pd-featured-stat"><span class="pd-featured-stat-label">30d net</span>${(agent.net_30d / 1e6).toLocaleString(undefined, { maximumFractionDigits: 2 })} USDC</span>`
								: '',
						]
							.filter(Boolean)
							.join('');
					}
					renderFeaturedAvatar(agent);
				} catch {
					nameEl.textContent = 'Couldn’t load featured agent';
					descEl.textContent =
						'The featured agent feed didn’t respond. Check connectivity in the Configuration tab, or retry.';
					if (statsEl) statsEl.hidden = true;
					const slot = $('pd-featured-avatar');
					if (slot) {
						slot.innerHTML =
							`<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:var(--ink-dim);font-size:0.8rem;text-align:center;padding:0.5rem">Unavailable</div>`;
					}
					// Turn the primary CTA into a retry so the card is recoverable
					// without a full page reload.
					if (linkEl) {
						linkEl.textContent = 'Retry';
						linkEl.href = '#dashboard';
						linkEl.onclick = (e) => {
							e.preventDefault();
							linkEl.onclick = null;
							loadFeaturedAgent();
						};
					}
				}
			}

			// ── Wallet snapshot ──────────────────────────────────────────

			// Task 02: real Solana wallet connect via src/wallet.js, balances via the
			// server-side POST /api/wallet/balances (Helius + Jupiter, key stays server-side).
			async function onWalletChanged(address) {
				const empty = $('pd-wallet-empty');
				const holdings = $('pd-wallet-holdings');
				const disconnectBtn = $('pd-wallet-disconnect');
				if (!holdings) return;
				state.walletAddress = address || null;

				if (!address) {
					holdings.hidden = true;
					holdings.innerHTML = '';
					if (empty) empty.hidden = false;
					if (disconnectBtn) disconnectBtn.hidden = true;
					return;
				}

				if (empty) empty.hidden = true;
				if (disconnectBtn) disconnectBtn.hidden = false;
				holdings.hidden = false;
				holdings.innerHTML =
					'<div style="font-size:0.85rem;color:var(--ink-dim)">Loading balances…</div>';

				try {
					const resp = await apiFetch('/api/wallet/balances', {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({ chain: 'solana', address }),
					});
					const data = await resp.json().catch(() => ({}));
					if (!resp.ok) {
						const msg =
							data.error_description ||
							data.error ||
							`Balance lookup failed (${resp.status})`;
						holdings.innerHTML = `<div style="font-size:0.85rem;color:var(--danger)">${escapeHtml(msg)}</div>`;
						return;
					}
					renderWalletHoldings(address, data);
				} catch (e) {
					holdings.innerHTML = `<div style="font-size:0.85rem;color:var(--danger)">Network error: ${escapeHtml(e.message || 'failed')}</div>`;
				}
			}

			// Deterministic, locally-drawn token-logo fallback (no external avatar
				// service). Produces a disc colored from the seed with the token's
				// leading character, returned as a data URI so a broken remote logo
				// can swap to it via onerror without another network request.
				const _tokenLogoFallbackCache = new Map();
				function tokenLogoFallback(seed, label) {
					const key = (seed || label || '?') + '|' + (label || '');
					const cached = _tokenLogoFallbackCache.get(key);
					if (cached) return cached;
					const size = 36; // 2× the 18px CSS box for crisp HiDPI
					const canvas = document.createElement('canvas');
					canvas.width = size;
					canvas.height = size;
					const ctx = canvas.getContext('2d');
					let uri = '';
					if (ctx) {
						let hash = 0;
						const s = String(seed || label || '?');
						for (let i = 0; i < s.length; i++)
							hash = (hash * 31 + s.charCodeAt(i)) >>> 0;
						const hue = hash % 360;
						ctx.fillStyle = 'hsl(' + hue + ' 58% 32%)';
						ctx.beginPath();
						ctx.arc(size / 2, size / 2, size / 2, 0, Math.PI * 2);
						ctx.fill();
						const ch =
							String(label || seed || '?')
								.replace(/^\$/, '')
								.trim()
								.charAt(0)
								.toUpperCase() || '?';
						ctx.fillStyle = 'hsl(' + hue + ' 70% 88%)';
						ctx.font = '600 18px system-ui, sans-serif';
						ctx.textAlign = 'center';
						ctx.textBaseline = 'middle';
						ctx.fillText(ch, size / 2, size / 2 + 1);
						uri = canvas.toDataURL('image/png');
					}
					_tokenLogoFallbackCache.set(key, uri);
					return uri;
				}

				function renderWalletHoldings(address, data) {
				const holdings = $('pd-wallet-holdings');
				const native = data.native || {};
				const solAmount = Number(native.amount || 0);
				const solUsd = Number(native.usd || 0);
				const tokens = (data.tokens || [])
					.map((t) => ({ ...t, usd: Number(t.usd || 0), amount: Number(t.amount || 0) }))
					.sort((a, b) => b.usd - a.usd)
					.slice(0, 10);

				holdings.innerHTML = `
					<div style="margin-bottom:0.6rem">
						<a class="pd-addr pd-mono" href="https://solscan.io/account/${escapeHtml(address)}" target="_blank" rel="noopener">${shortAddr(address)}</a>
					</div>
					<div class="pd-stat" style="margin-bottom:0.7rem">
						<div class="pd-stat-label">${escapeHtml(native.symbol || 'SOL')} balance</div>
						<div class="pd-stat-value">${solAmount.toLocaleString(undefined, { maximumFractionDigits: 4 })}</div>
						<div class="pd-stat-sub">${solUsd > 0 ? '$' + solUsd.toLocaleString(undefined, { maximumFractionDigits: 2 }) : '—'}</div>
					</div>
					<div style="font-size:0.78rem;color:var(--ink-dim);margin-bottom:0.45rem;font-family:var(--font-display);text-transform:uppercase;letter-spacing:0.08em">Top holdings</div>
					${
						tokens.length === 0
							? '<div style="font-size:0.85rem;color:var(--ink-dim)">No SPL tokens</div>'
							: `
						<table class="pd-table">
							<thead><tr><th>Token</th><th style="text-align:right">Amount</th><th style="text-align:right">USD</th></tr></thead>
							<tbody>
								${tokens
									.map(
										(t) => `
									<tr>
										<td>${(() => {
											const fallback = tokenLogoFallback(t.mint || t.symbol, t.symbol);
											const src = t.logo || fallback;
											// /inline-behaviors.js swaps a broken remote logo to the
											// local data-URI fallback exactly once, then drops the
											// image if that fails too.
											return `<img class="pd-token-logo" src="${escapeHtml(src)}" alt="" loading="lazy" data-fallback-src="${escapeHtml(fallback)}" data-fallback="remove" />`;
										})()}<span class="pd-mono">${escapeHtml(t.symbol || shortAddr(t.mint || ''))}</span></td>
										<td style="text-align:right" class="pd-mono">${t.amount.toLocaleString(undefined, { maximumFractionDigits: 4 })}</td>
										<td style="text-align:right" class="pd-mono">${t.usd > 0 ? '$' + t.usd.toLocaleString(undefined, { maximumFractionDigits: 2 }) : '—'}</td>
									</tr>
								`,
									)
									.join('')}
							</tbody>
						</table>
					`
					}
				`;
			}

			function disconnectWallet() {
				try {
					getConnectedWallet()?.disconnect?.();
				} catch {
					/* provider may already be disconnected */
				}
				onWalletChanged(null);
			}

			// ── Custom agents list ───────────────────────────────────────

			async function loadCustomAgents() {
				const tbody = $('pd-custom-agents-table');
				if (!tbody) return;
				tbody.innerHTML = '<tr><td colspan="4" class="pd-empty">Loading agents…</td></tr>';
				try {
					const resp = await apiFetch('/api/agents');
					if (resp.status === 401) {
						tbody.innerHTML =
							'<tr><td colspan="4" class="pd-empty">Sign in to manage your agents. <a href="/login" style="color:var(--accent)">Sign in</a></td></tr>';
						return;
					}
					if (!resp.ok) {
						tbody.innerHTML = `<tr><td colspan="4" class="pd-empty">Couldn’t load agents (${resp.status}).</td></tr>`;
						return;
					}
					const j = await resp.json();
					const agents = j.agents || j.data || [];
					if (!agents.length) {
						tbody.innerHTML = `<tr><td colspan="4">${emptyStateHTML({
							compact: true,
							icon: '🤖',
							title: 'No custom agents yet',
							body: 'Agents are AI characters with their own wallet and skills that you can embed and chat with. Spin one up to manage it here.',
							actions: [{ label: '+ New agent', href: '/create', primary: true }],
						})}</td></tr>`;
						return;
					}
					tbody.innerHTML = agents
						.map((a) => {
							const created = a.created_at
								? new Date(a.created_at).toLocaleDateString()
								: '—';
							const isFocused = a.id === state.agentId;
							return `<tr data-agent-row="${escapeHtml(a.id)}"${isFocused ? ' class="is-focused"' : ''}>
							<td>${escapeHtml(a.name || a.id)}</td>
							<td>${escapeHtml((a.description || '').slice(0, 80))}</td>
							<td class="pd-mono">${created}</td>
							<td>
								<a class="pd-btn pd-btn-sm" href="/agents/${escapeHtml(a.id)}/edit">Edit</a>
								<a class="pd-btn pd-btn-sm" href="/agents/${escapeHtml(a.id)}">Open</a>
								<button class="pd-btn pd-btn-sm is-danger" type="button" data-delete-agent="${escapeHtml(a.id)}" data-agent-name="${escapeHtml(a.name || a.id)}">Delete</button>
							</td>
						</tr>`;
						})
						.join('');
					tbody.querySelectorAll('[data-delete-agent]').forEach((b) => {
						b.addEventListener('click', () =>
							deleteAgent(b.dataset.deleteAgent, b.dataset.agentName),
						);
					});
					// Bring the deep-linked agent into view so the user lands on the row
					// for the coin they just launched.
					const focusedRow = tbody.querySelector('tr.is-focused');
					if (focusedRow)
						focusedRow.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
				} catch {
					tbody.innerHTML =
						'<tr><td colspan="4" class="pd-empty">Failed to load agents.</td></tr>';
				}
			}

			async function deleteAgent(id, name) {
				if (!confirm(`Delete agent "${name}"? This cannot be undone.`)) return;
				try {
					const csrf = await getCsrfToken();
					const headers = {};
					if (csrf) headers['x-csrf-token'] = csrf;
					const resp = await apiFetch('/api/agents/' + encodeURIComponent(id), {
						method: 'DELETE',
						headers,
					});
					if (resp.ok) {
						toast('Agent deleted', 'success');
						loadCustomAgents();
					} else {
						const err = await resp.json().catch(() => ({}));
						toast(
							err.error_description || err.error || `Delete failed (${resp.status})`,
							'error',
						);
					}
				} catch (e) {
					toast('Network error: ' + (e.message || 'delete failed'), 'error');
				}
			}

			// ── Agent control (postMessage to embedded iframe) ───────────

			async function loadAgent() {
				if (!state.agentId) {
					try {
						const resp = await apiFetch('/api/agents/me');
						if (resp.ok) {
							const { agent } = await resp.json();
							if (agent && agent.id) state.agentId = agent.id;
						}
					} catch {
						/* show empty state */
					}
				}
				// Load the embed for whichever agent we resolved — whether it came from
				// the ?agent= deep link or the account default. Guard against reloading
				// the same src so re-entering the page doesn't reset the live preview.
				if (state.agentId) {
					const iframe = $('pd-agent-iframe');
					const src = `/agent-embed.html?id=${encodeURIComponent(state.agentId)}`;
					if (iframe && iframe.getAttribute('src') !== src) iframe.src = src;
				}
				loadCustomAgents();
			}

			function postAgentAction(action) {
				const iframe = $('pd-agent-iframe');
				if (!iframe || !iframe.contentWindow || !state.agentId) {
					toast('Agent preview not ready yet', 'error');
					return false;
				}
				iframe.contentWindow.postMessage(
					{ agentId: state.agentId, type: 'agent:action', action },
					'*',
				);
				return true;
			}

			// Task 11: Speak posts a real TTS action; the embed plays ElevenLabs audio,
			// drives lip-sync, and replies with agent:action:result so we surface
			// real upstream errors instead of failing silently.
			function agentAction(type) {
				let action;
				switch (type) {
					case 'speak': {
						const text = $('pd-speech-input').value.trim();
						if (!text) {
							toast('Enter something to speak', 'error');
							return;
						}
						if (postAgentAction({ type: 'speak', text })) setSpeaking(true);
						return;
					}
					case 'emote':
						action = { type: 'emote', name: 'dance' };
						break;
					case 'wave':
						action = { type: 'gesture', name: 'wave' };
						break;
					case 'verify':
						action = { type: 'validate-model' };
						break;
					default:
						return;
				}
				postAgentAction(action);
			}

			function setSpeaking(on) {
				const speak = $('pd-speak-btn');
				const stop = $('pd-speak-stop');
				if (speak) speak.disabled = on;
				if (stop) stop.hidden = !on;
			}

			function stopSpeak() {
				postAgentAction({ type: 'speak:stop' });
				setSpeaking(false);
			}

			// Result + lifecycle messages from the agent embed.
			function handleAgentMessage(ev) {
				const msg = ev.data;
				if (!msg || typeof msg !== 'object') return;
				if (msg.type === 'agent:action:result') {
					const act = msg.action || {};
					if (act.type === 'speak' || act.type === 'speak:stop') {
						setSpeaking(false);
						if (msg.ok === false) toast(msg.error || 'Speech failed', 'error');
					}
				}
				// The embed echoes every protocol action; reset the Speak button when
				// playback finishes even if no explicit result arrives.
				if (msg.type === 'agent:action' && msg.action?.type === 'speak:end') {
					setSpeaking(false);
				}
			}

			function playAnimation() {
				const name = $('pd-anim-select').value.toLowerCase();
				const iframe = $('pd-agent-iframe');
				if (!iframe || !iframe.contentWindow || !state.agentId) return;
				iframe.contentWindow.postMessage(
					{
						agentId: state.agentId,
						type: 'agent:action',
						action: { type: 'gesture', name },
					},
					'*',
				);
			}

			// ── Channel feed (pre-populate Live Feed on load) ────────────

			function clearChannelFeedError() {
				const banner = $('pd-channel-feed-error');
				if (banner) banner.remove();
			}

			// Surfaces a recoverable error in the dashboard feed preview when the
			// channel-feed preload fails — otherwise the panel hangs on
			// "Waiting for the realtime feed…" with no way to recover before the
			// live WebSocket happens to deliver its first event.
			function showChannelFeedError() {
				const dashFeed = $('pd-dashboard-feed');
				if (!dashFeed) return;
				// If live events have already painted, don't cover them with an error.
				if (dashFeed.querySelector('.pd-feed-item')) return;
				clearChannelFeedError();
				const banner = document.createElement('div');
				banner.className = 'pd-feed-error';
				banner.id = 'pd-channel-feed-error';
				banner.setAttribute('role', 'alert');
				banner.innerHTML =
					'<div class="pd-feed-error-title">Couldn’t load recent activity</div>' +
					'<div class="pd-feed-error-msg">The activity feed didn’t respond. Live events will still stream in over the WebSocket once it connects.</div>';
				const btn = document.createElement('button');
				btn.type = 'button';
				btn.className = 'pd-btn pd-btn-sm';
				btn.textContent = 'Retry';
				btn.addEventListener('click', () => {
					btn.disabled = true;
					btn.textContent = 'Retrying…';
					preloadChannelFeed();
				});
				banner.appendChild(btn);
				const empty = dashFeed.querySelector('.pd-empty');
				if (empty) empty.remove();
				dashFeed.prepend(banner);
			}

			async function preloadChannelFeed() {
				try {
					const r = await fetch('/api/pump/channel-feed?limit=40');
					if (!r.ok) {
						showChannelFeedError();
						return;
					}
					const data = await r.json();
					const items = data.events || data.items || data;
					if (!Array.isArray(items)) {
						showChannelFeedError();
						return;
					}
					clearChannelFeedError();
					items
						.slice()
						.reverse()
						.forEach((evt) => {
							const type =
								evt.kind === 'mint'
									? 'launch'
									: evt.kind === 'whale'
										? 'whale'
										: evt.kind === 'claim'
											? 'claim'
											: evt.kind === 'signal'
												? 'signal'
												: 'trade';
							// buildFeed() normalises every item's time onto `ts` (unix
							// seconds); without it every preloaded row was stamped "now".
							handleWsEvent({
								type,
								...evt,
								timestamp: evt.ts || evt.created_at || evt.timestamp || Date.now(),
							});
						});
				} catch {
					showChannelFeedError();
				}
			}

			// ── WebSocket (PumpPortal realtime) ──────────────────────────

			// Exponential backoff with a hard cap. After MAX_RECONNECT_ATTEMPTS
			// consecutive failures we stop auto-retrying and surface a permanent
			// "feed stopped" state with a manual Reconnect button — otherwise a
			// sustained PumpPortal outage spins the page forever with no signal.
			const WS_BASE_BACKOFF_MS = 2000;
			const WS_MAX_BACKOFF_MS = 60000;
			const WS_MAX_RECONNECT_ATTEMPTS = 8;
			let wsReconnectAttempts = 0;
			let wsReconnectTimer = null;
			// Set while we are intentionally tearing the socket down (manual
			// reconnect / unload) so the onclose handler doesn't schedule a retry
			// on top of the fresh connection we're about to open.
			let wsClosingForReconnect = false;

			function clearWsDeadState() {
				const banner = $('pd-ws-dead-banner');
				if (banner) banner.remove();
			}

			// Renders the permanent dead-feed indicator into both feed panels
			// (dashboard preview + live feed) with a manual Reconnect control.
			function showWsDeadState() {
				const wsDot = $('pd-ws-dot');
				const wsLabel = $('pd-ws-status');
				if (wsDot) wsDot.className = 'pd-dot is-err';
				if (wsLabel) wsLabel.textContent = 'WS: feed stopped';

				clearWsDeadState();
				const banner = document.createElement('div');
				banner.className = 'pd-feed-error';
				banner.id = 'pd-ws-dead-banner';
				banner.setAttribute('role', 'alert');
				banner.innerHTML =
					'<div class="pd-feed-error-title">Realtime feed stopped</div>' +
					'<div class="pd-feed-error-msg">Could not reach the pump.fun stream after ' +
					WS_MAX_RECONNECT_ATTEMPTS +
					' attempts. PumpPortal may be temporarily down.</div>';
				const btn = document.createElement('button');
				btn.type = 'button';
				btn.className = 'pd-btn pd-btn-sm';
				btn.textContent = 'Reconnect';
				btn.addEventListener('click', () => {
					wsReconnectAttempts = 0;
					clearWsDeadState();
					connectWebSocket();
				});
				banner.appendChild(btn);

				// Prefer the live-feed page panel; mirror into the dashboard preview.
				const liveFeed = $('pd-live-feed');
				const dashFeed = $('pd-dashboard-feed');
				if (liveFeed) {
					const liveEmpty = liveFeed.querySelector('.pd-empty');
					if (liveEmpty && !liveFeed.querySelector('.pd-feed-item')) liveEmpty.remove();
					liveFeed.prepend(banner);
				} else if (dashFeed) {
					dashFeed.prepend(banner);
				}
			}

			function connectWebSocket() {
				if (wsReconnectTimer) {
					clearTimeout(wsReconnectTimer);
					wsReconnectTimer = null;
				}
				clearWsDeadState();
				if (state.ws) {
					wsClosingForReconnect = true;
					try {
						state.ws.close();
					} catch {}
					state.ws = null;
				}
				const wsDot = $('pd-ws-dot');
				const wsLabel = $('pd-ws-status');
				wsDot.className = 'pd-dot is-warm';
				wsLabel.textContent =
					wsReconnectAttempts > 0 ? 'WS: reconnecting…' : 'WS: connecting…';

				const scheduleReconnect = () => {
					if (wsReconnectAttempts >= WS_MAX_RECONNECT_ATTEMPTS) {
						showWsDeadState();
						return;
					}
					const delay = Math.min(
						WS_BASE_BACKOFF_MS * 2 ** wsReconnectAttempts,
						WS_MAX_BACKOFF_MS,
					);
					wsReconnectAttempts++;
					wsDot.className = 'pd-dot is-err';
					wsLabel.textContent = `WS: retry in ${Math.round(delay / 1000)}s`;
					wsReconnectTimer = setTimeout(connectWebSocket, delay);
				};

				try {
					wsClosingForReconnect = false;
					state.ws = new WebSocket(state.wsUrl);
					state.ws.onopen = () => {
						wsReconnectAttempts = 0;
						clearWsDeadState();
						wsDot.className = 'pd-dot is-on';
						wsLabel.textContent = 'WS: connected';
						if (/pumpportal\.fun/.test(state.wsUrl)) {
							try {
								state.ws.send(JSON.stringify({ method: 'subscribeNewToken' }));
								state.ws.send(JSON.stringify({ method: 'subscribeMigration' }));
							} catch {
								/* socket race; reconnect will retry */
							}
						}
					};
					state.ws.onmessage = (event) => {
						try {
							handleWsEvent(JSON.parse(event.data));
						} catch {
							/* ignore non-JSON */
						}
					};
					state.ws.onclose = () => {
						if (wsClosingForReconnect) {
							wsClosingForReconnect = false;
							return;
						}
						scheduleReconnect();
					};
					state.ws.onerror = () => {
						console.warn('[pump-dashboard] WebSocket error on', state.wsUrl);
						// onclose fires next and drives the backoff; just reflect the dot.
						wsDot.className = 'pd-dot is-err';
					};
				} catch (e) {
					console.warn('[pump-dashboard] WebSocket construct failed:', e?.message || e);
					scheduleReconnect();
				}
			}

			// Incoming events are queued and flushed once per animation frame. A busy
			// pump.fun feed can emit many events per second; rendering each one
			// synchronously thrashes layout and starves the main thread (jank, the
			// cursor stuttering during repaints). Batching coalesces that work.
			let _feedQueue = [];
			let _feedFlushRaf = 0;

			// PumpPortal identifies an event in `txType`, not `type`, and interleaves
			// subscription acknowledgements that carry no event at all. Without this
			// normalisation every live frame fell through to the generic branch of
			// addFeedItem and painted raw JSON into the feed.
			const WS_TX_TYPES = {
				create: 'launch',
				buy: 'buy',
				sell: 'sell',
				migrate: 'graduation',
				migration: 'graduation',
				complete: 'graduation',
			};
			// A trade this size is a whale print, and the feed has a Whales filter that
			// would otherwise never populate from a PumpPortal trade stream.
			const WHALE_SOL_THRESHOLD = 10;

			function feedEventType(data) {
				const raw = data.type || data.event || data.kind || data.txType;
				if (!raw) return null;
				const key = String(raw).toLowerCase();
				const mapped = WS_TX_TYPES[key] || key;
				if (
					(mapped === 'buy' || mapped === 'sell') &&
					Number(data.solAmount) >= WHALE_SOL_THRESHOLD
				)
					return 'whale';
				return mapped;
			}

			function handleWsEvent(data) {
				const type = feedEventType(data);
				if (!type) return;
				const ts = data.timestamp || Date.now();
				_feedQueue.push({
					type,
					time: new Date(typeof ts === 'number' && ts < 1e12 ? ts * 1000 : ts),
					data,
				});
				if (!_feedFlushRaf) _feedFlushRaf = requestAnimationFrame(flushFeedQueue);
			}

			function flushFeedQueue() {
				_feedFlushRaf = 0;
				const batch = _feedQueue;
				_feedQueue = [];
				if (!batch.length) return;

				// Suppress per-row entry animations during bursts — animating dozens of
				// prepended rows at once is the main source of feed jank.
				const burst = batch.length > 6;
				const liveFeed = $('pd-live-feed');
				const dashFeed = $('pd-dashboard-feed');
				if (burst) {
					liveFeed?.classList.add('pd-no-anim');
					dashFeed?.classList.add('pd-no-anim');
				}

				for (const item of batch) {
					addFeedItem('pd-live-feed', item);
					addFeedItem('pd-dashboard-feed', item);
					checkAlerts(item);
				}

				state.feedCount += batch.length;
				state.activityCount += batch.length;
				$('pd-feed-count').textContent = state.feedCount;
				$('pd-activity-count').textContent = state.activityCount;

				if (burst) {
					// Re-enable animations on the next frame, after the burst is painted.
					requestAnimationFrame(() => {
						liveFeed?.classList.remove('pd-no-anim');
						dashFeed?.classList.remove('pd-no-anim');
					});
				}
			}

			function addFeedItem(feedId, item) {
				if (state.feedPaused && feedId === 'pd-live-feed') return;
				const feed = $(feedId);
				if (!feed) return;
				const empty = feed.querySelector('.pd-empty');
				if (empty) empty.remove();
				// A live event arriving clears any recoverable error banners — the
				// feed is demonstrably working again.
				if (feedId === 'pd-dashboard-feed') clearChannelFeedError();
				const deadBanner = feed.querySelector('#pd-ws-dead-banner');
				if (deadBanner) deadBanner.remove();

				const div = document.createElement('div');
				div.className = 'pd-feed-item';
				div.dataset.type = item.type;

				const tagInfo = {
					launch: { cls: 'is-launch', label: 'LAUNCH' },
					create: { cls: 'is-launch', label: 'LAUNCH' },
					mint: { cls: 'is-launch', label: 'LAUNCH' },
					trade: { cls: 'is-buy', label: 'TRADE' },
					buy: { cls: 'is-buy', label: 'BUY' },
					sell: { cls: 'is-sell', label: 'SELL' },
					whale: { cls: 'is-whale', label: 'WHALE' },
					whale_trade: { cls: 'is-whale', label: 'WHALE' },
					graduation: { cls: 'is-grad', label: 'GRAD' },
					complete: { cls: 'is-grad', label: 'GRAD' },
					claim: { cls: 'is-claim', label: 'CLAIM' },
					fee_claim: { cls: 'is-claim', label: 'CLAIM' },
					signal: { cls: 'is-signal', label: 'SIGNAL' },
				}[item.type] || { cls: '', label: item.type.toUpperCase() };

				// Two shapes reach this renderer: live PumpPortal frames (structured
				// name/symbol/solAmount fields) and preloaded /api/pump/channel-feed
				// items (normalised to mint + ts + a prose `summary`). Every branch
				// reads the structured field first and falls back to the summary, so
				// neither source renders a blank or a zero.
				const d = item.data;
				const sym = d.symbol || d.tokenSymbol || '';
				const mintShort = d.mint ? shortAddr(d.mint) : '';
				const trader = d.user || d.traderPublicKey || d.wallet || '';
				const sol = Number(d.solAmount);
				const solStr =
					Number.isFinite(sol) && sol > 0 ? `${sol.toFixed(sol < 1 ? 4 : 2)} SOL` : '';
				const join = (...parts) => parts.filter(Boolean).join(' · ');
				let title = '',
					detail = '';
				if (item.type === 'launch' || item.type === 'create' || item.type === 'mint') {
					const name = d.name || d.tokenName || '';
					title = name
						? sym && sym !== name
							? `${name} (${sym})`
							: name
						: d.summary || sym || 'New token';
					detail = join(mintShort, solStr && `initial buy ${solStr}`);
				} else if (item.type === 'trade' || item.type === 'buy' || item.type === 'sell') {
					const side = item.type === 'buy' ? 'Buy' : item.type === 'sell' ? 'Sell' : 'Trade';
					title = join(`${side} ${sym || mintShort || 'token'}`, solStr) || d.summary;
					detail = join(trader && shortAddr(trader), sym ? mintShort : '');
				} else if (item.type === 'whale' || item.type === 'whale_trade') {
					const side = String(d.txType || '').toLowerCase() === 'sell' ? 'sell' : 'buy';
					title = solStr
						? join(`${solStr} ${side}`, sym || mintShort)
						: d.summary || 'Whale trade';
					detail = join(trader && shortAddr(trader), sym ? mintShort : '');
				} else if (item.type === 'graduation' || item.type === 'complete') {
					title = `${sym || d.name || 'Token'} graduated to AMM`;
					detail = join(mintShort, d.pool && `pool ${d.pool}`);
				} else if (item.type === 'claim' || item.type === 'fee_claim') {
					const amt = Number(d.amountSol);
					title =
						Number.isFinite(amt) && amt > 0
							? `${amt.toFixed(4)} SOL claimed`
							: d.summary || 'Fee claim';
					detail = join(d.claimType, d.claimerWallet && shortAddr(d.claimerWallet), mintShort);
				} else if (item.type === 'signal') {
					// Agent-attributed pump.fun reputation signal from pumpfun_signals.
					const w = Number(d.weight);
					const weightStr = Number.isFinite(w) && w !== 0 ? ` ${w > 0 ? '+' : ''}${w}` : '';
					title = d.summary || `${d.signal_kind || 'signal'}${weightStr}`;
					detail = mintShort || d.refs?.agent_name || d.agent_name || '';
				} else {
					title = d.summary || `${item.type} event`;
					detail = join(mintShort, trader && shortAddr(trader));
				}
				if (!title) title = d.summary || `${item.type} event`;

				const timeStr = item.time.toLocaleTimeString('en-US', { hour12: false });
				div.innerHTML = `
					<div class="pd-feed-time">${timeStr}</div>
					<div class="pd-feed-tag-col"><span class="pd-tag ${tagInfo.cls}">${escapeHtml(tagInfo.label)}</span></div>
					<div class="pd-feed-body">
						<div class="pd-feed-title">${escapeHtml(title)}</div>
						<div class="pd-feed-detail">${escapeHtml(detail)}</div>
					</div>
				`;
				// Only the live feed is filterable; hide the new row up front if it
				// doesn't match the active filter, instead of re-scanning all rows.
				if (
					feedId === 'pd-live-feed' &&
					!rowMatchesFilter(item.type, state.currentFilter)
				) {
					div.style.display = 'none';
				}

				feed.prepend(div);
				while (feed.children.length > 500) feed.lastElementChild.remove();
				if (feedId === 'pd-live-feed' && div.style.display !== 'none')
					$('pd-filter-empty')?.remove();
			}

			const FEED_FILTER_GROUPS = {
				launch: ['launch', 'create', 'mint'],
				trade: ['trade', 'buy', 'sell'],
				whale: ['whale', 'whale_trade'],
				graduation: ['graduation', 'complete'],
				claim: ['claim', 'fee_claim'],
			};

			function rowMatchesFilter(type, filter) {
				if (filter === 'all') return true;
				const matches = FEED_FILTER_GROUPS[filter] || [filter];
				return matches.includes(type || '');
			}

			const FEED_FILTER_LABELS = {
				launch: 'launches',
				trade: 'trades',
				whale: 'whale trades',
				graduation: 'graduations',
				claim: 'fee claims',
			};

			// A filter that matches nothing used to leave the panel blank, because every
			// row was simply display:none. Tell the user what is being filtered instead.
			function syncFilterEmptyState() {
				const feed = $('pd-live-feed');
				if (!feed) return;
				const existing = $('pd-filter-empty');
				const hasRows = feed.querySelector('.pd-feed-item');
				const hasVisible = Array.from(feed.querySelectorAll('.pd-feed-item')).some(
					(row) => row.style.display !== 'none',
				);
				if (!hasRows || hasVisible || state.currentFilter === 'all') {
					if (existing) existing.remove();
					return;
				}
				const label = FEED_FILTER_LABELS[state.currentFilter] || state.currentFilter;
				if (existing) {
					existing.querySelector('.pd-filter-empty-msg').textContent =
						`No ${label} in the feed yet. Events stream in live; switch back to All to see everything.`;
					return;
				}
				const box = document.createElement('div');
				box.className = 'pd-empty';
				box.id = 'pd-filter-empty';
				const msg = document.createElement('div');
				msg.className = 'pd-filter-empty-msg';
				msg.textContent = `No ${label} in the feed yet. Events stream in live; switch back to All to see everything.`;
				const btn = document.createElement('button');
				btn.type = 'button';
				btn.className = 'pd-btn pd-btn-sm';
				btn.textContent = 'Show all events';
				btn.addEventListener('click', () => setFeedFilter('all'));
				box.append(msg, btn);
				feed.prepend(box);
			}

			function setFeedFilter(filter) {
				state.currentFilter = filter;
				document.querySelectorAll('.pd-filter-btn').forEach((b) => {
					const on = b.dataset.filter === filter;
					b.classList.toggle('is-active', on);
					b.setAttribute('aria-pressed', on ? 'true' : 'false');
				});
				applyFeedFilter();
			}

			// Called only when the user changes the active filter — a full rescan is
			// correct here, but it no longer runs on every incoming feed event.
			function applyFeedFilter() {
				const feed = $('pd-live-feed');
				if (!feed) return;
				feed.querySelectorAll('.pd-feed-item').forEach((item) => {
					item.style.display = rowMatchesFilter(item.dataset.type, state.currentFilter)
						? ''
						: 'none';
				});
				syncFilterEmptyState();
			}

			function clearFeed(feedId) {
				const feed = $(feedId);
				if (!feed) return;
				feed.innerHTML = `<div class="pd-empty">
					<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 12c0-5 4-9 9-9"/><circle cx="5" cy="19" r="1.6" fill="currentColor" stroke="none"/></svg>
					<div>Cleared.</div>
				</div>`;
			}

			// -- Alerts (server-persisted rules) ----------------------------------
			// Alert rules live in Postgres and are evaluated server-side by the
			// pumpfun-monitor cron, so they fire across devices even with the tab closed.
			// localStorage is a render cache only. While the tab is open we ALSO match
			// live-feed events against the loaded rules for instant feedback.

			// Same-origin fetch: alert rules + notifications are three.ws's own endpoints,
			// never the user-configurable PumpKit API URL.
			function nativeFetch(path, options = {}) {
				return fetch(location.origin + path, { credentials: 'include', ...options });
			}
			async function nativeCsrf() {
				try {
					const r = await nativeFetch('/api/csrf-token');
					if (!r.ok) return null;
					const d = await r.json();
					return d.token || (d.data && d.data.token) || null;
				} catch {
					return null;
				}
			}

			const RULE_KIND_META = {
				graduation: { icon: '\u{1F393}', label: 'Graduation' },
				price_above: { icon: '\u{1F4C8}', label: 'Mcap above' },
				price_below: { icon: '\u{1F4C9}', label: 'Mcap below' },
				whale_buy: { icon: '\u{1F40B}', label: 'Whale buy' },
				new_mint: { icon: '\u{1F195}', label: 'New launch' },
				launch_match: { icon: '\u{1F3AF}', label: 'Launch match' },
			};
			const LAUNCH_FLAG_LABELS = {
				dev_dumped: 'dev dumped', bundle_launch: 'bundled', sniped: 'sniped',
				single_whale: 'single whale', low_diversity: 'low diversity', sell_pressure: 'sell pressure',
			};

			let _ruleEditingId = null;
			let _agentsLoaded = false;

			function relTime(ts) {
				const ms = Date.now() - new Date(ts).getTime();
				if (!Number.isFinite(ms)) return '';
				const s = Math.floor(ms / 1000);
				if (s < 60) return s + 's ago';
				const m = Math.floor(s / 60);
				if (m < 60) return m + 'm ago';
				const h = Math.floor(m / 60);
				if (h < 24) return h + 'h ago';
				return Math.floor(h / 24) + 'd ago';
			}
			function numOrNull(v) {
				const n = parseFloat(v);
				return Number.isFinite(n) ? n : null;
			}

			// Live-feed -> rule matching for instant, tab-open feedback. The authoritative
			// cross-session delivery is the server cron; this only mirrors it locally for
			// event kinds the raw feed actually carries (graduation, whale buys).
			function checkAlerts(item) {
				const rules = state.alertRules || [];
				if (!rules.length) return;
				const t = item.type;
				const d = item.data || {};
				const mint = d.mint || d.tokenMint || null;
				const solAmount = Number(d.solAmount != null ? d.solAmount : d.sol_amount || 0);
				for (const r of rules) {
					if (!r.enabled) continue;
					let hit = false;
					if (r.kind === 'graduation' && (t === 'graduation' || t === 'complete')) {
						hit = !r.target_mint || r.target_mint === mint;
					} else if (r.kind === 'whale_buy' && (t === 'whale' || t === 'whale_trade' || t === 'trade' || t === 'buy')) {
						hit = r.target_mint === mint && d.is_buy !== false && solAmount >= Number(r.threshold || 0);
					}
					if (hit) {
						const meta = RULE_KIND_META[r.kind];
						addAlertItem(item, meta.icon + ' ' + (r.label_display || r.label || meta.label));
					}
				}
			}

			function addAlertItem(item, label) {
				const feed = $('pd-alert-feed');
				if (!feed) return;
				const empty = feed.querySelector('.pd-empty');
				if (empty) empty.remove();
				const d = item.data || {};
				let detail = d.tokenSymbol || d.name || d.mint || '';
				if (d.solAmount) detail += ' · ' + Number(d.solAmount).toFixed(4) + ' SOL';
				const timeStr = item.time.toLocaleTimeString('en-US', { hour12: false });
				const div = document.createElement('div');
				div.className = 'pd-feed-item';
				div.innerHTML =
					'<div class="pd-feed-time">' + timeStr + '</div>' +
					'<div class="pd-feed-tag-col"></div>' +
					'<div class="pd-feed-body">' +
					'<div class="pd-feed-title" style="color:var(--warn)">' + escapeHtml(label) + '</div>' +
					'<div class="pd-feed-detail">' + escapeHtml(detail) + '</div>' +
					'</div>';
				feed.prepend(div);
				while (feed.children.length > 200) feed.lastElementChild.remove();
			}

			// Entry point on nav into #alerts.
			async function loadAlertConfig() {
				updateRuleFormFields();
				loadServerAlerts();
				await loadAlertRules();
			}

			async function loadServerAlerts() {
				try {
					const resp = await nativeFetch('/api/notifications?type=pump_alert&limit=50');
					if (!resp.ok) return;
					const { notifications } = await resp.json();
					if (!Array.isArray(notifications) || !notifications.length) return;
					notifications
						.slice()
						.reverse()
						.forEach((n) => {
							const p = n.payload || {};
							addAlertItem(
								{
									time: new Date(n.created_at),
									data: { name: p.name, tokenSymbol: p.symbol, mint: p.mint, solAmount: p.amount_sol },
								},
								serverAlertLabel(p),
							);
						});
				} catch {
					/* server history is best-effort */
				}
			}
			function serverAlertLabel(p) {
				const meta = RULE_KIND_META[p.kind] || { icon: '\u{1F514}', label: 'Alert' };
				const tok = p.symbol ? '$' + p.symbol : p.name || 'token';
				return meta.icon + ' ' + meta.label + ' · ' + tok;
			}

			async function loadAlertRules() {
				const list = $('pd-rules-list');
				if (!list) return;
				list.setAttribute('aria-busy', 'true');
				try {
					const resp = await nativeFetch('/api/alerts/rules');
					if (resp.status === 401) {
						state.alertRules = [];
						setRuleFormSignedOut(true);
						renderRulesSignedOut();
						return;
					}
					if (!resp.ok) {
						renderRulesError(resp.status);
						return;
					}
					const { rules } = await resp.json();
					state.alertRules = Array.isArray(rules) ? rules : [];
					safeStorage.setItem('pumpbot-alerts', JSON.stringify(state.alertRules));
					setRuleFormSignedOut(false);
					renderRulesList(state.alertRules);
					populateAgentOptions();
				} catch {
					// Network error: fall back to the cached render so rules still show.
					renderRulesList(state.alertRules || []);
				} finally {
					list.setAttribute('aria-busy', 'false');
				}
			}

			function renderRulesList(rules) {
				const list = $('pd-rules-list');
				if (!list) return;
				list.innerHTML = rules.length ? rules.map(ruleCardHTML).join('') : rulesEmptyHTML();
			}
			function rulesEmptyHTML() {
				return (
					'<div class="pd-empty pd-rules-empty">' +
					'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M5 16c0-4.5 1.5-10 7-10s7 5.5 7 10M3 16h18M10 19h4"/></svg>' +
					'<div><strong>No alert rules yet</strong></div>' +
					'<div class="pd-muted">Create your first rule on the left. Rules run on our servers and fire across every device — even with this tab closed.</div>' +
					'</div>'
				);
			}
			function renderRulesSignedOut() {
				const list = $('pd-rules-list');
				if (!list) return;
				list.innerHTML =
					'<div class="pd-empty">' +
					'<div><strong>Sign in to manage alerts</strong></div>' +
					'<div class="pd-muted">Server-side alerts are tied to your account so they follow you across devices.</div>' +
					'<a class="pd-btn is-primary pd-btn-sm" href="/login" style="margin-top:.6rem">Sign in</a>' +
					'</div>';
			}
			function renderRulesError(status) {
				const list = $('pd-rules-list');
				if (!list) return;
				list.innerHTML =
					'<div class="pd-empty">' +
					'<div><strong>Couldn’t load alert rules (' + status + ')</strong></div>' +
					'<div class="pd-muted">Check your connection, then use Refresh above.</div>' +
					'</div>';
			}

			function ruleSummaryHTML(r) {
				const short = (m) => (m ? escapeHtml(m.slice(0, 4) + '…' + m.slice(-4)) : '');
				const usd = (n) => '$' + Number(n).toLocaleString('en-US');
				switch (r.kind) {
					case 'graduation':
						if (r.target_mint) return 'When <span class="pd-mono">' + short(r.target_mint) + '</span> graduates to an AMM';
						if (r.target_agent) return 'When this agent’s token graduates to an AMM';
						return 'When any pump.fun token graduates to an AMM';
					case 'price_above':
						return 'When <span class="pd-mono">' + short(r.target_mint) + '</span> market cap rises above ' + usd(r.threshold);
					case 'price_below':
						return 'When <span class="pd-mono">' + short(r.target_mint) + '</span> market cap falls below ' + usd(r.threshold);
					case 'whale_buy':
						return 'When someone buys ≥ ' + escapeHtml(String(r.threshold)) + ' SOL of <span class="pd-mono">' + short(r.target_mint) + '</span>';
					case 'new_mint':
						return 'When this agent launches a new coin';
					case 'launch_match': {
						const f = r.filters || {};
						const parts = [];
						if (f.name_pattern) parts.push('named <span class="pd-mono">' + escapeHtml(f.name_pattern) + '</span>');
						if (f.min_market_cap_usd != null) parts.push('mcap ≥ ' + usd(f.min_market_cap_usd));
						if (f.max_market_cap_usd != null) parts.push('mcap ≤ ' + usd(f.max_market_cap_usd));
						if (f.min_safety_score != null) parts.push('safety ≥ ' + escapeHtml(String(f.min_safety_score)));
						if (f.min_creator_graduated != null) parts.push('creator with ≥ ' + escapeHtml(String(f.min_creator_graduated)) + ' graduated');
						if (f.max_creator_launches != null) parts.push('creator with ≤ ' + escapeHtml(String(f.max_creator_launches)) + ' earlier launches');
						if (Array.isArray(f.exclude_risk_flags) && f.exclude_risk_flags.length) parts.push('not ' + f.exclude_risk_flags.map((x) => escapeHtml(LAUNCH_FLAG_LABELS[x] || x)).join(', '));
						if (f.require_socials) parts.push('with socials');
						return 'When a new pump.fun coin launches' + (parts.length ? ': ' + parts.join(', ') : '');
					}
					default:
						return '';
				}
			}
			function channelChipsHTML(r) {
				const chips = [];
				if (r.deliver_in_app) chips.push('<span class="pd-chip">In-app</span>');
				if (r.webhook_url) chips.push('<span class="pd-chip">Webhook <button class="pd-chip-action" data-rule-reveal="' + escapeHtml(r.id) + '" aria-expanded="false" aria-controls="pd-secret-' + escapeHtml(r.id) + '" type="button">secret</button></span>');
				if (r.telegram_chat) chips.push('<span class="pd-chip">Telegram</span>');
				return chips.join('');
			}
			function deliveryStatusHTML(r) {
				if (!r.recent_failures) return '';
				const fail = (r.recent_deliveries || []).find((d) => d && d.ok === false);
				const detail = fail ? fail.channel + ': ' + (fail.detail || 'failed') : '';
				return (
					'<div class="pd-rule-fail">⚠ ' + r.recent_failures + ' delivery failure' + (r.recent_failures > 1 ? 's' : '') +
					' in 24h' + (detail ? ' — ' + escapeHtml(detail) : '') + '</div>'
				);
			}
			function ruleCardHTML(r) {
				const meta = RULE_KIND_META[r.kind] || { icon: '\u{1F514}', label: 'Alert' };
				const last = r.last_fired_at ? 'Last fired ' + relTime(r.last_fired_at) : 'Not fired yet';
				return (
					'<div class="pd-rule-card' + (r.enabled ? '' : ' is-disabled') + '" data-rule-id="' + escapeHtml(r.id) + '">' +
					'<div class="pd-rule-icon" aria-hidden="true">' + meta.icon + '</div>' +
					'<div class="pd-rule-body">' +
					'<div class="pd-rule-title">' + escapeHtml(r.label_display || r.label || meta.label) + '</div>' +
					'<div class="pd-rule-summary">' + ruleSummaryHTML(r) + '</div>' +
					'<div class="pd-rule-tags">' +
					channelChipsHTML(r) +
					'<span class="pd-rule-tag">Cooldown ' + r.cooldown_seconds + 's</span>' +
					'<span class="pd-rule-tag' + (r.last_fired_at ? '' : ' pd-muted') + '">' + last + '</span>' +
					'</div>' +
					'<div class="pd-rule-secret-row" id="pd-secret-' + escapeHtml(r.id) + '" hidden data-secret-for="' + escapeHtml(r.id) + '">' +
					'<span class="pd-muted">Signing secret:</span> ' +
					'<code class="pd-rule-secret-code">' + escapeHtml(r.webhook_secret || '—') + '</code> ' +
					'<button class="pd-btn pd-btn-xs" data-rule-copy="' + escapeHtml(r.id) + '" type="button">Copy</button>' +
					'</div>' +
					deliveryStatusHTML(r) +
					'</div>' +
					'<div class="pd-rule-actions">' +
					'<label class="pd-switch" title="' + (r.enabled ? 'Enabled — click to disable' : 'Disabled — click to enable') + '">' +
					'<input type="checkbox" data-rule-toggle="' + escapeHtml(r.id) + '" ' + (r.enabled ? 'checked' : '') + ' aria-label="' + (r.enabled ? 'Disable' : 'Enable') + ' alert: ' + escapeHtml(r.label_display || r.label || meta.label) + '" />' +
					'<span class="pd-switch-track"><span class="pd-switch-thumb"></span></span>' +
					'</label>' +
					'<button class="pd-btn pd-btn-sm" data-rule-edit="' + escapeHtml(r.id) + '" type="button">Edit</button>' +
					'<button class="pd-btn pd-btn-sm is-danger" data-rule-delete="' + escapeHtml(r.id) + '" type="button">Delete</button>' +
					'</div>' +
					'</div>'
				);
			}

			async function populateAgentOptions() {
				const sel = $('pd-rule-agent');
				if (!sel || _agentsLoaded) return;
				try {
					const resp = await nativeFetch('/api/agents');
					if (!resp.ok) return;
					const j = await resp.json();
					const agents = j.agents || j.data || [];
					const cur = sel.value;
					sel.innerHTML =
						'<option value="">Select an agent…</option>' +
						agents.map((a) => '<option value="' + escapeHtml(a.id) + '">' + escapeHtml(a.name || a.id) + '</option>').join('');
					if (cur) sel.value = cur;
					_agentsLoaded = true;
				} catch {
					/* leave the placeholder option */
				}
			}

			function updateRuleFormFields() {
				const kind = $('pd-rule-kind').value;
				const scopeGroup = $('pd-rule-scope-group');
				const mintGroup = $('pd-rule-mint-group');
				const agentGroup = $('pd-rule-agent-group');
				const thrGroup = $('pd-rule-threshold-group');
				const hint = $('pd-rule-kind-hint');
				$('pd-rule-launch-group').hidden = kind !== 'launch_match';
				scopeGroup.hidden = true;
				mintGroup.hidden = true;
				agentGroup.hidden = true;
				thrGroup.hidden = true;
				if (kind === 'graduation') {
					scopeGroup.hidden = false;
					const scope = $('pd-rule-scope').value;
					if (scope === 'mint') mintGroup.hidden = false;
					else if (scope === 'agent') {
						agentGroup.hidden = false;
						populateAgentOptions();
					}
					hint.textContent = 'Fires when a pump.fun token migrates to an AMM.';
				} else if (kind === 'price_above' || kind === 'price_below') {
					mintGroup.hidden = false;
					thrGroup.hidden = false;
					$('pd-rule-threshold-label').textContent = 'Market cap (USD)';
					$('pd-rule-threshold').min = '1';
					$('pd-rule-threshold').step = '1';
					$('pd-rule-threshold-hint').textContent =
						kind === 'price_above'
							? 'Alert when the token’s USD market cap rises above this value.'
							: 'Alert when the token’s USD market cap falls below this value.';
					hint.textContent = 'Tracks the token’s live USD market cap.';
				} else if (kind === 'whale_buy') {
					mintGroup.hidden = false;
					thrGroup.hidden = false;
					$('pd-rule-threshold-label').textContent = 'Minimum buy size (SOL)';
					$('pd-rule-threshold').min = '0.01';
					$('pd-rule-threshold').step = '0.01';
					$('pd-rule-threshold-hint').textContent = 'Alert on any buy at or above this many SOL.';
					hint.textContent = 'Watches buys on a specific token.';
				} else if (kind === 'new_mint') {
					agentGroup.hidden = false;
					populateAgentOptions();
					hint.textContent = 'Fires when the selected agent launches a new coin.';
				} else if (kind === 'launch_match') {
					hint.textContent = 'Fires for every new pump.fun launch that passes all of these filters, about 90 seconds after it launches, once coin intel has scored it.';
				}
			}

			function readLaunchFilters() {
				const f = {};
				const name = $('pd-rule-lf-name').value.trim();
				if (name) f.name_pattern = name;
				const nums = { min_market_cap_usd: 'pd-rule-lf-mcmin', max_market_cap_usd: 'pd-rule-lf-mcmax', min_safety_score: 'pd-rule-lf-safety', min_creator_graduated: 'pd-rule-lf-grads', max_creator_launches: 'pd-rule-lf-launches' };
				for (const [key, id] of Object.entries(nums)) {
					const v = numOrNull($(id).value);
					if (v != null) f[key] = v;
				}
				const flags = [...document.querySelectorAll('[data-lf-flag]:checked')].map((el) => el.dataset.lfFlag);
				if (flags.length) f.exclude_risk_flags = flags;
				if ($('pd-rule-lf-socials').checked) f.require_socials = true;
				return f;
			}

			function writeLaunchFilters(f) {
				f = f || {};
				$('pd-rule-lf-name').value = f.name_pattern || '';
				$('pd-rule-lf-mcmin').value = f.min_market_cap_usd != null ? f.min_market_cap_usd : '';
				$('pd-rule-lf-mcmax').value = f.max_market_cap_usd != null ? f.max_market_cap_usd : '';
				$('pd-rule-lf-safety').value = f.min_safety_score != null ? f.min_safety_score : '';
				$('pd-rule-lf-grads').value = f.min_creator_graduated != null ? f.min_creator_graduated : '';
				$('pd-rule-lf-launches').value = f.max_creator_launches != null ? f.max_creator_launches : '';
				const ex = new Set(f.exclude_risk_flags || []);
				document.querySelectorAll('[data-lf-flag]').forEach((el) => { el.checked = ex.has(el.dataset.lfFlag); });
				$('pd-rule-lf-socials').checked = !!f.require_socials;
			}

			function buildRulePayload() {
				const kind = $('pd-rule-kind').value;
				const p = {
					kind,
					deliver_in_app: $('pd-rule-inapp').checked,
					webhook_url: $('pd-rule-webhook').value.trim() || null,
					telegram_chat: $('pd-rule-telegram').value.trim() || null,
					cooldown_seconds: parseInt($('pd-rule-cooldown').value, 10) || 300,
					label: $('pd-rule-label').value.trim() || null,
				};
				if (kind === 'graduation') {
					const scope = $('pd-rule-scope').value;
					if (scope === 'mint') p.target_mint = $('pd-rule-mint').value.trim() || null;
					else if (scope === 'agent') p.target_agent = $('pd-rule-agent').value || null;
				} else if (kind === 'price_above' || kind === 'price_below' || kind === 'whale_buy') {
					p.target_mint = $('pd-rule-mint').value.trim() || null;
					p.threshold = numOrNull($('pd-rule-threshold').value);
				} else if (kind === 'new_mint') {
					p.target_agent = $('pd-rule-agent').value || null;
				} else if (kind === 'launch_match') {
					p.filters = readLaunchFilters();
				}
				return p;
			}

			function validateRuleClient(p) {
				if (p.kind === 'price_above' || p.kind === 'price_below' || p.kind === 'whale_buy') {
					if (!p.target_mint) return 'Enter a token mint address.';
					if (!(p.threshold > 0)) return 'Enter a threshold greater than 0.';
				}
				if (p.kind === 'new_mint' && !p.target_agent) return 'Select an agent.';
				if (p.kind === 'launch_match') {
					if (!Object.keys(p.filters || {}).length) return 'Set at least one launch filter.';
					const f = p.filters;
					if (f.min_market_cap_usd != null && f.max_market_cap_usd != null && f.min_market_cap_usd > f.max_market_cap_usd) return 'Min market cap cannot exceed max market cap.';
					if (f.min_safety_score != null && (f.min_safety_score < 0 || f.min_safety_score > 100)) return 'Safety score is between 0 and 100.';
				}
				if (p.kind === 'graduation') {
					const scope = $('pd-rule-scope').value;
					if (scope === 'mint' && !p.target_mint) return 'Enter a token mint address.';
					if (scope === 'agent' && !p.target_agent) return 'Select an agent.';
				}
				if (p.webhook_url && !/^https:\/\//i.test(p.webhook_url)) return 'Webhook URL must start with https://';
				if (!p.deliver_in_app && !p.webhook_url && !p.telegram_chat) return 'Enable at least one delivery channel.';
				if (!(p.cooldown_seconds >= 5)) return 'Cooldown must be at least 5 seconds.';
				return null;
			}

			async function saveRule() {
				const payload = buildRulePayload();
				const err = validateRuleClient(payload);
				if (err) {
					toast(err, 'error');
					return;
				}
				const btn = $('pd-rule-save');
				btn.disabled = true;
				btn.textContent = _ruleEditingId ? 'Saving…' : 'Creating…';
				try {
					const csrf = await nativeCsrf();
					const headers = { 'Content-Type': 'application/json' };
					if (csrf) headers['x-csrf-token'] = csrf;
					const path = _ruleEditingId ? '/api/alerts/rules/' + _ruleEditingId : '/api/alerts/rules';
					const httpMethod = _ruleEditingId ? 'PATCH' : 'POST';
					const resp = await nativeFetch(path, { method: httpMethod, headers, body: JSON.stringify(payload) });
					if (resp.status === 401) {
						toast('Sign in to save alerts across devices', 'error');
						setRuleFormSignedOut(true);
						return;
					}
					if (!resp.ok) {
						const e = await resp.json().catch(() => ({}));
						toast(e.error_description || e.error || 'Save failed (' + resp.status + ')', 'error');
						return;
					}
					const data = await resp.json();
					const wasEditing = !!_ruleEditingId;
					toast(wasEditing ? 'Alert rule updated' : 'Alert rule created', 'success');
					if (data.rule && data.rule.webhook_secret && payload.webhook_url) {
						toast('Webhook secret ready — open “secret” on the rule to copy it.', 'info');
					}
					resetRuleForm();
					await loadAlertRules();
				} catch (e) {
					toast('Network error: ' + (e.message || 'save failed'), 'error');
				} finally {
					btn.disabled = false;
					btn.textContent = _ruleEditingId ? 'Update alert rule' : 'Create alert rule';
				}
			}

			function editRule(id) {
				const r = (state.alertRules || []).find((x) => x.id === id);
				if (!r) return;
				_ruleEditingId = id;
				$('pd-rule-kind').value = r.kind;
				if (r.kind === 'graduation') {
					$('pd-rule-scope').value = r.target_mint ? 'mint' : r.target_agent ? 'agent' : 'global';
				}
				$('pd-rule-mint').value = r.target_mint || '';
				$('pd-rule-threshold').value = r.threshold != null ? r.threshold : '';
				$('pd-rule-label').value = r.label || '';
				$('pd-rule-inapp').checked = !!r.deliver_in_app;
				$('pd-rule-webhook').value = r.webhook_url || '';
				$('pd-rule-telegram').value = r.telegram_chat || '';
				$('pd-rule-cooldown').value = r.cooldown_seconds || 300;
				writeLaunchFilters(r.kind === 'launch_match' ? r.filters : null);
				updateRuleFormFields();
				// Agent options may load async; set the value once they're present.
				const applyAgent = () => {
					if (r.target_agent) $('pd-rule-agent').value = r.target_agent;
				};
				applyAgent();
				populateAgentOptions().then(applyAgent);
				$('pd-rule-form-title').textContent = 'Edit alert rule';
				$('pd-rule-save').textContent = 'Update alert rule';
				$('pd-rule-cancel').hidden = false;
				$('page-alerts').scrollIntoView({ behavior: 'smooth', block: 'start' });
			}

			function resetRuleForm() {
				_ruleEditingId = null;
				$('pd-rule-kind').value = 'graduation';
				$('pd-rule-scope').value = 'global';
				$('pd-rule-mint').value = '';
				if ($('pd-rule-agent')) $('pd-rule-agent').value = '';
				$('pd-rule-threshold').value = '';
				$('pd-rule-label').value = '';
				$('pd-rule-inapp').checked = true;
				$('pd-rule-webhook').value = '';
				$('pd-rule-telegram').value = '';
				$('pd-rule-cooldown').value = '300';
				writeLaunchFilters(null);
				updateRuleFormFields();
				$('pd-rule-form-title').textContent = 'New alert rule';
				$('pd-rule-save').textContent = 'Create alert rule';
				$('pd-rule-cancel').hidden = true;
			}

			function setRuleFormSignedOut(disabled) {
				const note = $('pd-rule-signin-note');
				if (note) note.hidden = !disabled;
				const ids = ['pd-rule-kind', 'pd-rule-scope', 'pd-rule-mint', 'pd-rule-agent', 'pd-rule-threshold', 'pd-rule-label', 'pd-rule-inapp', 'pd-rule-webhook', 'pd-rule-telegram', 'pd-rule-cooldown', 'pd-rule-save', 'pd-rule-cancel'];
				ids.forEach((id) => {
					const el = $(id);
					if (el) el.disabled = disabled;
				});
				const launchGroup = $('pd-rule-launch-group');
				if (launchGroup) launchGroup.disabled = disabled;
			}

			async function deleteRule(id) {
				const r = (state.alertRules || []).find((x) => x.id === id);
				const name = r ? ' (' + (r.label_display || r.label || r.kind) + ')' : '';
				if (!confirm('Delete this alert rule' + name + '? This can’t be undone.')) return;
				try {
					const csrf = await nativeCsrf();
					const headers = {};
					if (csrf) headers['x-csrf-token'] = csrf;
					const resp = await nativeFetch('/api/alerts/rules/' + id, { method: 'DELETE', headers });
					if (!resp.ok && resp.status !== 404) {
						const e = await resp.json().catch(() => ({}));
						toast(e.error_description || 'Delete failed (' + resp.status + ')', 'error');
						return;
					}
					toast('Alert rule deleted', 'success');
					if (_ruleEditingId === id) resetRuleForm();
					await loadAlertRules();
				} catch (e) {
					toast('Network error: ' + (e.message || 'delete failed'), 'error');
				}
			}

			async function toggleRule(id, enabled) {
				try {
					const csrf = await nativeCsrf();
					const headers = { 'Content-Type': 'application/json' };
					if (csrf) headers['x-csrf-token'] = csrf;
					const resp = await nativeFetch('/api/alerts/rules/' + id, { method: 'PATCH', headers, body: JSON.stringify({ enabled }) });
					if (!resp.ok) {
						const e = await resp.json().catch(() => ({}));
						toast(e.error_description || 'Update failed (' + resp.status + ')', 'error');
						await loadAlertRules();
						return;
					}
					const data = await resp.json();
					const idx = (state.alertRules || []).findIndex((x) => x.id === id);
					if (idx >= 0 && data.rule) {
						state.alertRules[idx] = data.rule;
						const card = document.querySelector('[data-rule-id="' + (window.CSS && CSS.escape ? CSS.escape(id) : id) + '"]');
						if (card) card.classList.toggle('is-disabled', !enabled);
					}
					toast(enabled ? 'Rule enabled' : 'Rule disabled', 'success');
				} catch {
					toast('Network error', 'error');
					await loadAlertRules();
				}
			}

			function copyRuleSecret(id) {
				const r = (state.alertRules || []).find((x) => x.id === id);
				if (!r || !r.webhook_secret) return;
				if (navigator.clipboard) {
					navigator.clipboard.writeText(r.webhook_secret).then(
						() => toast('Webhook secret copied', 'success'),
						() => toast('Copy failed — select the text manually', 'error'),
					);
				}
			}

			function onRulesListClick(e) {
				const t = e.target.closest('[data-rule-edit],[data-rule-delete],[data-rule-reveal],[data-rule-copy]');
				if (!t) return;
				if (t.dataset.ruleEdit) editRule(t.dataset.ruleEdit);
				else if (t.dataset.ruleDelete) deleteRule(t.dataset.ruleDelete);
				else if (t.dataset.ruleReveal) {
					const sel = '[data-secret-for="' + (window.CSS && CSS.escape ? CSS.escape(t.dataset.ruleReveal) : t.dataset.ruleReveal) + '"]';
					const row = document.querySelector(sel);
					if (row) {
						row.hidden = !row.hidden;
						t.setAttribute('aria-expanded', row.hidden ? 'false' : 'true');
					}
				} else if (t.dataset.ruleCopy) copyRuleSecret(t.dataset.ruleCopy);
			}
			function onRulesListChange(e) {
				const t = e.target.closest('[data-rule-toggle]');
				if (!t) return;
				toggleRule(t.dataset.ruleToggle, t.checked);
			}

			// ── Watches ──────────────────────────────────────────────────

			// Watches live on a PumpKit deployment, not on three.ws. When the API URL
			// still points at this origin there is nothing to call, so render the
			// guidance directly instead of firing a request that can only 404.
			function watchesUnsupported() {
				const tbody = $('pd-watches-table');
				tbody.innerHTML = `<tr><td colspan="6" class="pd-empty">Watches require a PumpKit-style API. Point the API URL in <a href="#config" data-page-link="config" class="pd-mono" style="color:var(--accent)">Configuration</a> at your PumpKit deployment.</td></tr>`;
				$('pd-watches-count').textContent = '0';
				state.watchesSupported = false;
				bindPageLinks();
			}

			function watchesApiConfigured() {
				try {
					return new URL(state.apiUrl, location.origin).origin !== location.origin;
				} catch {
					return false;
				}
			}

			async function refreshWatches() {
				const tbody = $('pd-watches-table');
				if (!watchesApiConfigured()) {
					watchesUnsupported();
					return;
				}
				tbody.innerHTML = '<tr><td colspan="6" class="pd-empty">Loading…</td></tr>';
				try {
					const resp = await apiFetch('/api/v1/watches?limit=100');
					if (resp.status === 404) {
						watchesUnsupported();
						return;
					}
					state.watchesSupported = true;
					if (!resp.ok) {
						tbody.innerHTML = `<tr><td colspan="6" class="pd-empty">Upstream unavailable (${resp.status}).</td></tr>`;
						return;
					}
					const data = await resp.json();
					const watches = data.data || data.watches || [];
					$('pd-watches-count').textContent = String(watches.length);
					if (watches.length === 0) {
						tbody.innerHTML =
							'<tr><td colspan="6" class="pd-empty">No watches yet. Click <strong>+ Add watch</strong> to create one.</td></tr>';
						return;
					}
					tbody.innerHTML = watches
						.map(
							(w) => `
						<tr>
							<td><a class="pd-addr" href="https://solscan.io/account/${escapeHtml(w.wallet)}" target="_blank" rel="noopener">${shortAddr(w.wallet)}</a></td>
							<td>${escapeHtml(w.label || '—')}</td>
							<td class="pd-mono">${w.tokenFilter ? w.tokenFilter.map(shortAddr).join(', ') : 'All'}</td>
							<td>${w.webhookUrl ? '<span class="pd-tag is-buy">on</span>' : '—'}</td>
							<td class="pd-mono">${w.createdAt ? new Date(w.createdAt).toLocaleDateString() : '—'}</td>
							<td><button class="pd-btn pd-btn-sm is-danger" data-delete-watch="${escapeHtml(w.id)}" type="button">Delete</button></td>
						</tr>
					`,
						)
						.join('');
					tbody.querySelectorAll('[data-delete-watch]').forEach((b) => {
						b.addEventListener('click', () => deleteWatch(b.dataset.deleteWatch));
					});
				} catch (e) {
					tbody.innerHTML = `<tr><td colspan="6" class="pd-empty">Error: ${escapeHtml(e.message || 'load failed')}</td></tr>`;
				}
			}

			async function createWatch() {
				const wallet = $('pd-watch-wallet').value.trim();
				if (!wallet) {
					toast('Wallet address is required', 'error');
					return;
				}
				const tokenFilterRaw = $('pd-watch-token-filter').value.trim();
				const body = {
					wallet,
					label: $('pd-watch-label').value.trim() || undefined,
					tokenFilter: tokenFilterRaw
						? tokenFilterRaw
								.split(',')
								.map((s) => s.trim())
								.filter(Boolean)
						: undefined,
					webhookUrl: $('pd-watch-webhook').value.trim() || undefined,
				};
				try {
					const resp = await apiFetch('/api/v1/watches', {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify(body),
					});
					if (resp.ok) {
						toast('Watch created', 'success');
						closeModal('pd-add-watch-modal');
						refreshWatches();
						[
							'pd-watch-wallet',
							'pd-watch-label',
							'pd-watch-token-filter',
							'pd-watch-webhook',
						].forEach((id) => {
							$(id).value = '';
						});
					} else {
						const err = await resp.json().catch(() => ({}));
						toast(err.error || 'Failed to create watch', 'error');
					}
				} catch {
					toast('Network error creating watch', 'error');
				}
			}

			async function deleteWatch(id) {
				if (!confirm('Delete this watch?')) return;
				try {
					const resp = await apiFetch('/api/v1/watches/' + encodeURIComponent(id), {
						method: 'DELETE',
					});
					if (resp.ok) {
						toast('Watch deleted', 'success');
						refreshWatches();
					} else {
						toast('Failed to delete watch', 'error');
					}
				} catch {
					toast('Network error', 'error');
				}
			}

			// ── Claims ───────────────────────────────────────────────────

			async function refreshClaims() {
				const wallet = $('pd-claims-wallet-filter').value.trim().toLowerCase();
				const claimType = $('pd-claims-type-filter').value;
				const tbody = $('pd-claims-table');
				tbody.innerHTML = '<tr><td colspan="6" class="pd-empty">Loading…</td></tr>';
				try {
					const resp = await apiFetch('/api/agents/pumpfun?op=claims&limit=50');
					if (resp.status === 401) {
						tbody.innerHTML =
							'<tr><td colspan="6" class="pd-empty">Sign in to view fee claims.</td></tr>';
						return;
					}
					if (!resp.ok) {
						tbody.innerHTML = `<tr><td colspan="6" class="pd-empty">Upstream unavailable (${resp.status}).</td></tr>`;
						return;
					}
					const data = await resp.json();
					let claims = (data.items || data.claims || data.data || []).slice();
					if (wallet)
						claims = claims.filter((c) =>
							String(c.claimerWallet || c.wallet || '')
								.toLowerCase()
								.includes(wallet),
						);
					if (claimType)
						claims = claims.filter((c) => {
							const t = (
								c.claimType ||
								(c.isCashback ? 'cashback' : 'creator_fee') ||
								''
							).toLowerCase();
							return t === claimType.toLowerCase();
						});
					$('pd-claims-count').textContent = String(claims.length);
					if (!claims.length) {
						tbody.innerHTML =
							'<tr><td colspan="6" class="pd-empty">No claims match this filter.</td></tr>';
						return;
					}
					tbody.innerHTML = claims
						.map((c) => {
							const ts = c.timestamp || c.time || c.at;
							const isCashback =
								c.isCashback || (c.claimType || '').toLowerCase() === 'cashback';
							const typeClass = isCashback ? 'is-claim' : 'is-buy';
							const typeLabel = isCashback
								? 'Cashback'
								: c.claimType || 'Creator Fee';
							const wal = c.claimerWallet || c.wallet || '';
							const tx = c.txSignature || c.signature || '';
							const sym =
								c.tokenSymbol || c.tokenName || shortAddr(c.tokenMint || '');
							const amt = Number(c.amountSol ?? c.amount ?? 0);
							return `
							<tr>
								<td class="pd-mono">${ts ? new Date(ts).toLocaleString() : '—'}</td>
								<td><a class="pd-addr" href="https://solscan.io/account/${escapeHtml(wal)}" target="_blank" rel="noopener">${shortAddr(wal)}</a></td>
								<td><span class="pd-tag ${typeClass}">${escapeHtml(typeLabel)}</span></td>
								<td class="pd-mono">${escapeHtml(sym)}</td>
								<td class="pd-mono" style="color:var(--success)">${amt.toFixed(4)} SOL</td>
								<td>${tx ? `<a class="pd-addr" href="https://solscan.io/tx/${escapeHtml(tx)}" target="_blank" rel="noopener">${shortAddr(tx)}</a>` : '—'}</td>
							</tr>
						`;
						})
						.join('');
				} catch (e) {
					tbody.innerHTML = `<tr><td colspan="6" class="pd-empty">Error: ${escapeHtml(e.message || 'load failed')}</td></tr>`;
				}
			}

			function exportClaims() {
				const rows = document.querySelectorAll('#pd-claims-table tr');
				if (!rows.length) return;
				let csv = 'Time,Wallet,Type,Token,Amount SOL,TX\n';
				rows.forEach((tr) => {
					const cells = tr.querySelectorAll('td');
					if (cells.length >= 6) {
						csv +=
							Array.from(cells)
								.map((c) => '"' + c.textContent.trim().replace(/"/g, '""') + '"')
								.join(',') + '\n';
					}
				});
				const blob = new Blob([csv], { type: 'text/csv' });
				const url = URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = 'pumpfun-claims-' + new Date().toISOString().slice(0, 10) + '.csv';
				document.body.appendChild(a);
				a.click();
				a.remove();
				URL.revokeObjectURL(url);
				toast('Claims exported', 'success');
			}

			// ── Token Scanner ────────────────────────────────────────────

			// A scan is two on-chain reads that routinely take several seconds, so the
			// button and this line carry the busy state. A toast alone was not enough:
			// it expires, leaving a failed scan indistinguishable from one never run.
			function setScanStatus(text, kind = 'info') {
				const el = $('pd-scan-status');
				if (!el) return;
				el.textContent = text || '';
				el.hidden = !text;
				el.classList.toggle('is-error', kind === 'error');
			}

			async function scanToken() {
				const mint = $('pd-scanner-mint').value.trim();
				if (!mint) {
					toast('Enter a token mint address', 'error');
					setScanStatus('Enter a token mint address to scan.', 'error');
					$('pd-scanner-mint').focus();
					return;
				}
				$('pd-scanner-results').hidden = true;
				const scanBtn = $('pd-scan-token');
				const scanLabel = scanBtn.textContent;
				scanBtn.disabled = true;
				scanBtn.textContent = 'Scanning…';
				setScanStatus('Reading the mint account and top holders on-chain…');
				try {
					const [scanData, holdersData] = await Promise.all([
						rpcCall(
							{
								method: 'getAccountInfo',
								params: [mint, { encoding: 'jsonParsed' }],
							},
							{ id: 1 },
						),
						rpcCall(
							{
								method: 'getTokenLargestAccounts',
								params: [mint],
							},
							{ id: 2 },
						),
					]);
					const account = scanData.result?.value;
					if (!account) {
						toast('Token not found on-chain', 'error');
						setScanStatus(
							'No account exists at that address on mainnet. Check the mint and scan again.',
							'error',
						);
						return;
					}

					const info = account.data?.parsed?.info || {};
					const holders = holdersData.result?.value || [];
					const checks = {};
					let score = 100;

					const owner = account.owner;
					checks.program = {
						status: 'info',
						detail:
							owner === 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'
								? 'SPL Token'
								: owner === 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'
									? 'Token-2022'
									: owner,
					};

					if (info.mintAuthority) {
						checks.mintAuth = {
							status: 'warn',
							detail: 'Active: ' + shortAddr(info.mintAuthority),
						};
						score -= 15;
					} else checks.mintAuth = { status: 'pass', detail: 'Revoked' };

					if (info.freezeAuthority) {
						checks.freezeAuth = {
							status: 'fail',
							detail: 'Active: ' + shortAddr(info.freezeAuthority),
						};
						score -= 25;
					} else checks.freezeAuth = { status: 'pass', detail: 'None' };

					const totalSupply = Number(info.supply || 0);
					let topConc = 0;
					if (holders.length > 0 && totalSupply > 0) {
						topConc = parseFloat(
							((Number(holders[0].amount || 0) / totalSupply) * 100).toFixed(2),
						);
					}
					if (topConc > 50) {
						checks.concentration = {
							status: 'warn',
							detail: `Top holder: ${topConc}%`,
						};
						score -= 10;
					} else
						checks.concentration = {
							status: 'pass',
							detail: `Top holder: ${topConc}%`,
						};

					const decimals = info.decimals || 0;
					const displaySupply = (
						Number(info.supply || 0) / Math.pow(10, decimals)
					).toLocaleString();
					checks.supply = {
						status: 'info',
						detail: `${displaySupply} (${decimals} decimals)`,
					};

					let isPump = false;
					try {
						const bcData = await rpcCall(
							{
								method: 'getProgramAccounts',
								params: [
									'6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P',
									{
										filters: [{ memcmp: { offset: 30, bytes: mint } }],
										dataSlice: { offset: 0, length: 1 },
									},
								],
							},
							{ id: 3 },
						);
						isPump = bcData.result && bcData.result.length > 0;
					} catch {
						// Optional enrichment; rpcCall already logged + flagged. The
						// core scan still completes without the pump-curve check.
					}

					if (isPump) {
						checks.pumpfun = {
							status: 'pass',
							detail: 'Bonding curve active — sells guaranteed by AMM',
						};
						score = Math.min(score + 10, 100);
					} else checks.pumpfun = { status: 'info', detail: 'Not a Pump.fun token' };

					if (isPump) {
						try {
							const curveResp = await fetch(
								`/api/pump/curve?mint=${encodeURIComponent(mint)}`,
							);
							if (curveResp.ok) {
								const curve = await curveResp.json();
								if (curve.price?.priceSol)
									checks.spot_price = {
										status: 'info',
										detail: `${Number(curve.price.priceSol).toFixed(8)} SOL/token`,
									};
								if (curve.price?.marketCapSol)
									checks.market_cap = {
										status: 'info',
										detail: `${Number(curve.price.marketCapSol).toFixed(2)} SOL`,
									};
								if (curve.graduation?.progressBps != null) {
									const pct = Number(curve.graduation.progressBps) / 100;
									checks.graduation = {
										status: pct >= 80 ? 'warn' : 'pass',
										detail: `${pct.toFixed(1)}% to graduation`,
									};
								}
							}
						} catch {
							/* curve enrichment optional */
						}
					}

					const riskLevel = score >= 80 ? 'LOW' : score >= 50 ? 'MEDIUM' : 'HIGH';
					const riskClass =
						score >= 80 ? 'is-success' : score >= 50 ? 'is-warn' : 'is-danger';

					$('pd-scan-score').textContent = score + '/100';
					$('pd-scan-score').className = 'pd-stat-value ' + riskClass;
					$('pd-scan-level').textContent = riskLevel;
					$('pd-scan-level').className = 'pd-stat-value ' + riskClass;
					$('pd-scan-pump').textContent = isPump ? 'Yes' : 'No';
					$('pd-scan-pump').className = 'pd-stat-value ' + (isPump ? 'is-success' : '');
					$('pd-scan-honeypot').textContent = info.freezeAuthority
						? 'Risk'
						: isPump
							? 'Safe (AMM)'
							: 'Safe';
					$('pd-scan-honeypot').className =
						'pd-stat-value ' + (info.freezeAuthority ? 'is-danger' : 'is-success');

					const statusTagClass = {
						pass: 'is-buy',
						warn: 'is-whale',
						fail: 'is-sell',
						info: 'is-launch',
					};
					const tbody = $('pd-scan-checks');
					tbody.innerHTML = Object.entries(checks)
						.map(
							([name, c]) => `
						<tr>
							<td>${escapeHtml(name)}</td>
							<td><span class="pd-tag ${statusTagClass[c.status] || ''}">${c.status.toUpperCase()}</span></td>
							<td class="pd-mono">${escapeHtml(c.detail)}</td>
						</tr>
					`,
						)
						.join('');
					$('pd-scanner-results').hidden = false;
					setScanStatus('');
					toast(
						'Scan complete: ' + riskLevel.toLowerCase() + ' risk',
						riskLevel === 'HIGH' ? 'error' : 'success',
					);
				} catch (e) {
					const why = e.message || 'the network request failed';
					toast('Scan failed: ' + why, 'error');
					setScanStatus(`Scan failed: ${why}. Press Scan to try again.`, 'error');
				} finally {
					scanBtn.disabled = false;
					scanBtn.textContent = scanLabel;
				}
			}

			// ── Quote Engine ─────────────────────────────────────────────

			function formatPriceContext(p) {
				const parts = [];
				if (p.priceSol) parts.push(`${(Number(p.priceSol) || 0).toFixed(8)} SOL/token`);
				if (p.marketCapSol)
					parts.push(`MC ${(Number(p.marketCapSol) || 0).toFixed(2)} SOL`);
				return parts.join(' · ');
			}

			function renderQuoteResult(target, opts) {
				const { amountLabel, amountText, impact, mc } = opts;
				target.innerHTML = `
					<div style="padding:0.85rem 1rem;background:var(--surface-1);border-radius:var(--radius-md);border:1px solid var(--stroke)">
						<div style="font-family:var(--font-display);font-size:0.66rem;text-transform:uppercase;letter-spacing:0.1em;color:var(--ink-dim);margin-bottom:0.25rem">${escapeHtml(amountLabel)}</div>
						<div style="font-family:var(--font-mono);font-size:1.35rem;color:var(--accent);margin-bottom:0.35rem">${escapeHtml(amountText)}</div>
						<div style="font-size:0.78rem;color:var(--ink-dim)">Price impact <span style="color:${impact > 5 ? 'var(--warn)' : 'var(--success)'}">${impact.toFixed(2)}%</span></div>
						${mc ? `<div style="font-size:0.74rem;color:var(--ink-dim);margin-top:0.35rem">Spot: ${escapeHtml(formatPriceContext(mc))}</div>` : ''}
					</div>
				`;
			}

			// /api/pump/quote-sdk answers with { error, error_description }. Showing the
			// raw code ("internal_error", "no_curve") told the user nothing and offered
			// no next step, so translate the ones this page can actually hit.
			const QUOTE_ERROR_TEXT = {
				no_curve:
					'No active bonding curve for that mint. It has graduated to an AMM, or the address is not a pump.fun token.',
				bad_mint: 'That is not a valid Solana mint address.',
				bad_amount: 'Enter an amount greater than zero.',
				bad_side: 'Quote side must be buy or sell.',
				upstream_unavailable:
					'Every Solana RPC provider is rate limited right now. Try again in a moment.',
			};

			function quoteErrorText(status, data) {
				const code = data?.error;
				if (QUOTE_ERROR_TEXT[code]) return QUOTE_ERROR_TEXT[code];
				if (status >= 500)
					return 'The quote service could not reach Solana. Try again in a moment.';
				return data?.error_description || data?.message || 'Quote failed.';
			}

			async function getBuyQuote() {
				const mint = $('pd-quote-buy-mint').value.trim();
				const solAmount = parseFloat($('pd-quote-buy-amount').value);
				if (!mint) {
					toast('Enter token mint', 'error');
					return;
				}
				if (!Number.isFinite(solAmount) || solAmount <= 0) {
					toast('Enter a positive SOL amount', 'error');
					return;
				}
				const target = $('pd-quote-buy-result');
				target.innerHTML = '<span style="color:var(--ink-dim)">Calculating…</span>';
				try {
					const r = await fetch(
						`/api/pump/quote-sdk?mint=${encodeURIComponent(mint)}&side=buy&amount=${solAmount}`,
					);
					const data = await r.json();
					if (!r.ok) {
						target.innerHTML = `<span style="color:var(--danger)">${escapeHtml(quoteErrorText(r.status, data))}</span>`;
						return;
					}
					renderQuoteResult(target, {
						amountLabel: 'You receive',
						amountText: `${Number(data.output?.tokensUi || 0).toLocaleString(undefined, { maximumFractionDigits: 2 })} tokens for ${solAmount} SOL`,
						impact: Number(data.priceImpactPct || 0),
						mc: data.marketContext,
					});
				} catch (e) {
					target.innerHTML = `<span style="color:var(--danger)">Error: ${escapeHtml(e.message || 'Quote failed')}</span>`;
				}
			}

			async function getSellQuote() {
				const mint = $('pd-quote-sell-mint').value.trim();
				const tokenAmount = parseFloat($('pd-quote-sell-amount').value);
				if (!mint) {
					toast('Enter token mint', 'error');
					return;
				}
				if (!Number.isFinite(tokenAmount) || tokenAmount <= 0) {
					toast('Enter a positive token amount', 'error');
					return;
				}
				const target = $('pd-quote-sell-result');
				target.innerHTML = '<span style="color:var(--ink-dim)">Calculating…</span>';
				try {
					const r = await fetch(
						`/api/pump/quote-sdk?mint=${encodeURIComponent(mint)}&side=sell&amount=${tokenAmount}`,
					);
					const data = await r.json();
					if (!r.ok) {
						target.innerHTML = `<span style="color:var(--danger)">${escapeHtml(quoteErrorText(r.status, data))}</span>`;
						return;
					}
					renderQuoteResult(target, {
						amountLabel: 'You receive',
						amountText: `${Number(data.output?.sol || 0).toFixed(6)} SOL for ${tokenAmount.toLocaleString()} tokens`,
						impact: Number(data.priceImpactPct || 0),
						mc: data.marketContext,
					});
				} catch (e) {
					target.innerHTML = `<span style="color:var(--danger)">Error: ${escapeHtml(e.message || 'Quote failed')}</span>`;
				}
			}

			// ── Vanity Generator ─────────────────────────────────────────

			async function startVanity() {
				const prefix = $('pd-vanity-prefix').value.trim();
				const suffix = $('pd-vanity-suffix').value.trim();
				if (!prefix && !suffix) {
					toast('Enter a prefix or suffix', 'error');
					return;
				}
				if (prefix) {
					const v = validatePattern(prefix);
					if (!v.valid) {
						toast(`Prefix: ${v.errors.join('; ')}`, 'error');
						return;
					}
				}
				if (suffix) {
					const v = validatePattern(suffix);
					if (!v.valid) {
						toast(`Suffix: ${v.errors.join('; ')}`, 'error');
						return;
					}
				}
				state.vanityAbort = new AbortController();
				$('pd-vanity-start').hidden = true;
				$('pd-vanity-stop').hidden = false;
				$('pd-vanity-status').textContent = 'Spinning up workers…';
				$('pd-vanity-result').innerHTML = '';
				try {
					const result = await grindVanity({
						prefix: prefix || undefined,
						suffix: suffix || undefined,
						signal: state.vanityAbort.signal,
						onProgress: ({ attempts, rate, eta }) => {
							$('pd-vanity-status').textContent =
								`${attempts.toLocaleString()} tries · ${Math.round(rate).toLocaleString()}/s · eta ${eta}`;
						},
					});
					const secretJson = JSON.stringify(Array.from(result.secretKey));
					const secretB58 = b58encode(result.secretKey);
					const seconds = (result.durationMs / 1000).toFixed(1);
					$('pd-vanity-status').textContent =
						`Found in ${seconds}s · ${result.attempts.toLocaleString()} attempts · ${result.workers} worker${result.workers > 1 ? 's' : ''}`;
					$('pd-vanity-result').innerHTML = `
						<div style="padding:0.85rem 1rem;background:var(--surface-1);border-radius:var(--radius-md);border:1px solid var(--stroke-strong)">
							<div style="font-family:var(--font-display);font-size:0.66rem;text-transform:uppercase;letter-spacing:0.1em;color:var(--ink-dim);margin-bottom:0.25rem">Public key</div>
							<div class="pd-mono" style="font-size:0.92rem;color:var(--ink);word-break:break-all;margin-bottom:0.55rem">${escapeHtml(result.publicKey)}</div>
							<div style="display:flex;gap:0.4rem;flex-wrap:wrap">
								<button class="pd-btn pd-btn-sm" id="pd-vanity-copy-pub" type="button">Copy address</button>
								<button class="pd-btn pd-btn-sm" id="pd-vanity-reveal" type="button">Reveal secret key</button>
								<button class="pd-btn pd-btn-sm" id="pd-vanity-download-key" type="button">Download keypair JSON</button>
							</div>
							<div id="pd-vanity-secret" hidden style="margin-top:0.6rem">
								<div style="font-family:var(--font-display);font-size:0.66rem;text-transform:uppercase;letter-spacing:0.1em;color:var(--danger);margin-bottom:0.25rem">Secret key (base58)</div>
								<div class="pd-mono" id="pd-vanity-secret-val" style="font-size:0.8rem;color:var(--accent);word-break:break-all;margin-bottom:0.45rem"></div>
								<button class="pd-btn pd-btn-sm" id="pd-vanity-copy-secret" type="button">Copy secret</button>
							</div>
							<div class="pd-callout" style="margin-top:0.6rem;font-size:0.78rem">Secret key never leaves your browser. Save it securely or import into a wallet.</div>
						</div>
					`;
					$('pd-vanity-copy-pub').addEventListener('click', async () => {
						try {
							await navigator.clipboard.writeText(result.publicKey);
							toast('Address copied', 'success');
						} catch {}
					});
					$('pd-vanity-reveal').addEventListener('click', () => {
						const box = $('pd-vanity-secret');
						const btn = $('pd-vanity-reveal');
						const showing = !box.hidden;
						if (showing) {
							box.hidden = true;
							$('pd-vanity-secret-val').textContent = '';
							btn.textContent = 'Reveal secret key';
						} else {
							$('pd-vanity-secret-val').textContent = secretB58;
							box.hidden = false;
							btn.textContent = 'Hide secret key';
						}
					});
					$('pd-vanity-copy-secret').addEventListener('click', async () => {
						try {
							await navigator.clipboard.writeText(secretB58);
							toast('Secret key copied', 'success');
						} catch {}
					});
					$('pd-vanity-download-key').addEventListener('click', () => {
						const blob = new Blob([secretJson], { type: 'application/json' });
						const url = URL.createObjectURL(blob);
						const a = document.createElement('a');
						a.href = url;
						a.download = `vanity-${result.publicKey.slice(0, 8)}.json`;
						document.body.appendChild(a);
						a.click();
						a.remove();
						URL.revokeObjectURL(url);
					});
					toast('Vanity address found', 'success');
				} catch (e) {
					if (e?.name === 'AbortError') $('pd-vanity-status').textContent = 'Stopped';
					else {
						$('pd-vanity-status').textContent = `Error: ${e.message || 'grind failed'}`;
						toast('Grind failed', 'error');
					}
				} finally {
					state.vanityAbort = null;
					$('pd-vanity-start').hidden = false;
					$('pd-vanity-stop').hidden = true;
				}
			}

			function stopVanity() {
				state.vanityAbort?.abort();
				state.vanityAbort = null;
				$('pd-vanity-start').hidden = false;
				$('pd-vanity-stop').hidden = true;
			}

			// ── Config ───────────────────────────────────────────────────

			// Task 10: persist, reconnect, then probe each endpoint for real and
			// reflect the live result inline next to each field.
			function setProbe(id, state_, detail) {
				const el = $(id);
				if (!el) return;
				el.className = 'pd-probe is-' + state_;
				el.textContent =
					state_ === 'ok'
						? 'OK'
						: state_ === 'pending'
							? 'Testing…'
							: `Failed: ${detail || 'error'}`;
				el.title = detail || '';
			}

			async function probeApi() {
				try {
					const r = await fetch(state.apiUrl.replace(/\/$/, '') + '/api/healthz', {
						signal: AbortSignal.timeout(5000),
					});
					if (!r.ok) return { ok: false, detail: `HTTP ${r.status}` };
					const d = await r.json().catch(() => ({}));
					return d.ok || d.status === 'ok'
						? { ok: true, detail: 'healthy' }
						: { ok: false, detail: 'no ok flag' };
				} catch (e) {
					return { ok: false, detail: e.name === 'TimeoutError' ? 'timeout' : e.message };
				}
			}

			async function probeApiKey() {
				if (!state.apiKey) return { ok: false, detail: 'no key set' };
				try {
					const r = await fetch(state.apiUrl.replace(/\/$/, '') + '/api/v1/status', {
						headers: { 'X-API-Key': state.apiKey },
						signal: AbortSignal.timeout(5000),
					});
					if (r.ok) return { ok: true, detail: 'authorized' };
					if (r.status === 401 || r.status === 403)
						return { ok: false, detail: `${r.status} unauthorized` };
					return { ok: false, detail: `HTTP ${r.status}` };
				} catch (e) {
					return { ok: false, detail: e.name === 'TimeoutError' ? 'timeout' : e.message };
				}
			}

			function probeWs() {
				return new Promise((resolve) => {
					let settled = false;
					let sock;
					const done = (ok, detail) => {
						if (settled) return;
						settled = true;
						try {
							sock?.close();
						} catch {}
						resolve({ ok, detail });
					};
					try {
						sock = new WebSocket(state.wsUrl);
						sock.onopen = () => done(true, 'connected');
						sock.onerror = () => done(false, 'connection error');
						setTimeout(() => done(false, 'timeout'), 3000);
					} catch (e) {
						done(false, e.message);
					}
				});
			}

			async function probeRpc() {
				try {
					const r = await fetch(state.rpcUrl, {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }),
						signal: AbortSignal.timeout(5000),
					});
					const d = await r.json().catch(() => ({}));
					if (d.result === 'ok') return { ok: true, detail: 'healthy' };
					if (d.error) return { ok: false, detail: d.error.message || 'rpc error' };
					return { ok: false, detail: `HTTP ${r.status}` };
				} catch (e) {
					return { ok: false, detail: e.name === 'TimeoutError' ? 'timeout' : e.message };
				}
			}

			async function runConfigProbes() {
				setProbe('pd-probe-api', 'pending');
				setProbe('pd-probe-key', 'pending');
				setProbe('pd-probe-ws', 'pending');
				setProbe('pd-probe-rpc', 'pending');
				const [api, key, ws, rpc] = await Promise.all([
					probeApi(),
					probeApiKey(),
					probeWs(),
					probeRpc(),
				]);
				setProbe('pd-probe-api', api.ok ? 'ok' : 'err', api.detail);
				setProbe('pd-probe-key', key.ok ? 'ok' : 'err', key.detail);
				setProbe('pd-probe-ws', ws.ok ? 'ok' : 'err', ws.detail);
				setProbe('pd-probe-rpc', rpc.ok ? 'ok' : 'err', rpc.detail);
			}

			async function saveConfig() {
				state.apiUrl = $('pd-cfg-api-url').value.trim() || location.origin;
				state.wsUrl = $('pd-cfg-ws-url').value.trim() || 'wss://pumpportal.fun/api/data';
				state.apiKey = $('pd-cfg-api-key').value.trim();
				state.rpcUrl = $('pd-cfg-rpc-url').value.trim() || '/api/solana-rpc';
				safeStorage.setItem('pumpbot-api-url', state.apiUrl);
				safeStorage.setItem('pumpbot-ws-url', state.wsUrl);
				safeStorage.setItem('pumpbot-api-key', state.apiKey);
				safeStorage.setItem('pumpbot-rpc-url', state.rpcUrl);
				$('pd-api-endpoint-display').textContent = state.apiUrl;
				connectApi();
				// A manual save is an explicit retry — reset the backoff so the new
				// endpoint gets a full attempt and any dead-feed banner is cleared.
				wsReconnectAttempts = 0;
				connectWebSocket();
				toast('Configuration saved — testing connections', 'success');

				const btn = $('pd-save-config');
				const original = btn.textContent;
				btn.disabled = true;
				btn.textContent = 'Testing…';
				try {
					await runConfigProbes();
				} finally {
					btn.disabled = false;
					btn.textContent = original;
				}
			}

			// ── Modals ───────────────────────────────────────────────────

			function openModal(id) {
				const backdrop = $(id);
				if (!backdrop) return;
				backdrop.classList.add('is-open');
				const focusable =
					backdrop.querySelector('input, select, textarea') ||
					backdrop.querySelector('button');
				focusable?.focus();
			}
			function closeModal(id) {
				$(id)?.classList.remove('is-open');
			}
			// Escape closes the topmost open modal; backdrop-click closes that modal.
			// Wired once at init via initModalDismiss().
			function initModalDismiss() {
				document.addEventListener('keydown', (e) => {
					if (e.key !== 'Escape') return;
					const open = document.querySelector('.pd-modal-backdrop.is-open');
					if (open) closeModal(open.id);
				});
				document
					.querySelectorAll('.pd-modal-backdrop')
					.forEach((backdrop) => {
						backdrop.addEventListener('click', (e) => {
							if (e.target === backdrop) closeModal(backdrop.id);
						});
					});
			}

			// ── Uptime ───────────────────────────────────────────────────

			function updateUptime() {
				const elapsed = Date.now() - state.startupAt;
				const h = Math.floor(elapsed / 3600000);
				const m = Math.floor((elapsed % 3600000) / 60000);
				const s = Math.floor((elapsed % 60000) / 1000);
				$('pd-uptime').textContent = `Uptime: ${h}h ${m}m ${s}s`;
			}

			// ── Internal page-link binder (for #links that switch SPA tab) ─

			function bindPageLinks() {
				document.querySelectorAll('[data-page-link]').forEach((a) => {
					a.addEventListener(
						'click',
						(e) => {
							e.preventDefault();
							navigateTo(a.dataset.pageLink);
						},
						{ once: true },
					);
				});
			}

			// ── CSRF (single-use, fetched fresh per mutation) ────────────
			async function getCsrfToken() {
				try {
					const r = await apiFetch('/api/csrf-token');
					if (!r.ok) return null;
					const d = await r.json();
					return d.token || d.data?.token || null;
				} catch {
					return null;
				}
			}

			// ── base58 encode (for revealing the vanity secret key) ──────
			function b58encode(bytes) {
				const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
				const digits = [0];
				for (let i = 0; i < bytes.length; i++) {
					let carry = bytes[i];
					for (let j = 0; j < digits.length; j++) {
						carry += digits[j] << 8;
						digits[j] = carry % 58;
						carry = (carry / 58) | 0;
					}
					while (carry > 0) {
						digits.push(carry % 58);
						carry = (carry / 58) | 0;
					}
				}
				let str = '';
				for (let i = 0; i < bytes.length && bytes[i] === 0; i++) str += '1';
				for (let i = digits.length - 1; i >= 0; i--) str += ALPHABET[digits[i]];
				return str;
			}

			function relTimeIso(iso) {
				const diff = Date.now() - new Date(iso).getTime();
				const m = Math.floor(diff / 60000);
				if (m < 1) return 'just now';
				if (m < 60) return m + 'm ago';
				const h = Math.floor(m / 60);
				if (h < 24) return h + 'h ago';
				return Math.floor(h / 24) + 'd ago';
			}

			// ════════════════════════════════════════════════════════════
			//  Monitor stat cards (Task 07) — bound to GET /api/healthz
			// ════════════════════════════════════════════════════════════
			function formatUptime(sec) {
				const h = Math.floor(sec / 3600),
					m = Math.floor((sec % 3600) / 60),
					s = Math.floor(sec % 60);
				if (h > 0) return `${h}h ${m}m`;
				if (m > 0) return `${m}m ${s}s`;
				return `${s}s`;
			}
			function setMonitorStale(stale) {
				const grid = $('pd-monitor-stats');
				if (grid)
					grid.querySelectorAll('.pd-stat').forEach((c) =>
						c.classList.toggle('is-stale', stale),
					);
				const sub = $('stat-bot-status-sub');
				if (sub)
					sub.innerHTML = stale
						? 'Live monitor <span class="pd-stale-badge">stale</span>'
						: 'Live monitor';
			}
			async function pollMonitorStats() {
				try {
					const r = await apiFetch('/api/healthz');
					if (!r.ok) throw new Error('health ' + r.status);
					const d = await r.json();
					const m = d.monitor || {};
					setMonitorStale(false);
					$('stat-bot-status').textContent = m.running ? 'Running' : 'Stopped';
					$('stat-bot-status').className =
						'pd-stat-value ' + (m.running ? 'is-success' : 'is-danger');
					$('stat-bot-mode').textContent = m.mode || '—';
					$('stat-claims').textContent = Number(m.claimsDetected ?? 0).toLocaleString();
					$('stat-watches').textContent = Number(
						(d.watches || {}).total ?? 0,
					).toLocaleString();
					$('stat-uptime').textContent = formatUptime(d.uptime || 0);
				} catch {
					// Keep last real values, flag stale.
					setMonitorStale(true);
				}
			}

			// ════════════════════════════════════════════════════════════
			//  Canvas helpers for the market chart
			// ════════════════════════════════════════════════════════════
			function setupCanvas(canvas) {
				const dpr = window.devicePixelRatio || 1;
				const w = canvas.clientWidth || canvas.parentElement.clientWidth || 600;
				const h = canvas.clientHeight || 280;
				canvas.width = Math.round(w * dpr);
				canvas.height = Math.round(h * dpr);
				const ctx = canvas.getContext('2d');
				ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
				return { ctx, w, h };
			}
			function cssVar(name) {
				return (
					getComputedStyle(document.documentElement).getPropertyValue(name).trim() ||
					'#fff'
				);
			}
			function fmtPrice(v) {
				const n = Number(v);
				if (!isFinite(n)) return '—';
				if (n >= 1) return n.toLocaleString(undefined, { maximumFractionDigits: 2 });
				if (n >= 0.01) return n.toFixed(4);
				if (n > 0) return n.toPrecision(3);
				return '0';
			}
			function drawChartMessage(canvas, msg) {
				const { ctx, w, h } = setupCanvas(canvas);
				ctx.clearRect(0, 0, w, h);
				ctx.strokeStyle = 'rgba(255,255,255,0.05)';
				ctx.lineWidth = 1;
				for (let i = 1; i < 5; i++) {
					const y = (h * i) / 5;
					ctx.beginPath();
					ctx.moveTo(0, y);
					ctx.lineTo(w, y);
					ctx.stroke();
				}
				ctx.fillStyle = 'rgba(255,255,255,0.42)';
				ctx.font = '12px system-ui';
				ctx.textAlign = 'center';
				ctx.textBaseline = 'middle';
				ctx.fillText(msg === 'skeleton' ? 'Loading…' : msg, w / 2, h / 2);
			}

			// ════════════════════════════════════════════════════════════
			//  Market chart (Tasks 03 + 04)
			// ════════════════════════════════════════════════════════════
			const chart = { candles: [], mint: '', symbol: '', spotUsd: null, geom: null };

			// The $THREE flagship — our cockpit's default chart token. Pinned client-side
			// too so the market chart renders instantly and never hangs on a slow or
			// unavailable trending feed.
			const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';

			function selectChartToken(mint, symbol) {
				if (chart.mint === mint) return;
				document.dispatchEvent(
					new CustomEvent('chart:tokenChange', { detail: { mint, symbol } }),
				);
			}

			// Render $THREE as an immediate, real default option + chart while the live
			// trending list loads (or if it never does).
			function ensureThreeDefault(sel) {
				if (sel.value) return;
				sel.innerHTML = `<option value="${THREE_MINT}" data-symbol="THREE">★  THREE  (${escapeHtml(shortAddr(THREE_MINT))})</option>`;
				sel.selectedIndex = 0;
				selectChartToken(THREE_MINT, 'THREE');
			}

			async function loadTrendingTokens() {
				const sel = $('pd-chart-token');
				if (!sel) return;
				$('pd-chart-retry').hidden = true;
				ensureThreeDefault(sel);
				try {
					const r = await fetch('/api/pump/trending?limit=25');
					const d = await r.json().catch(() => ({}));
					// Tolerate both the normalized { data: [...] } shape and a bare array.
					const feed = Array.isArray(d) ? d : Array.isArray(d.data) ? d.data : [];
					if (!r.ok || !feed.length) return; // keep the $THREE default in place

					// Pin the $THREE flagship first (de-duped), then the live market below it.
					const three = { mint: THREE_MINT, symbol: 'THREE', flagship: true };
					const tokens = [three, ...feed.filter((t) => t.mint !== THREE_MINT)];

					const prevMint = chart.mint;
					sel.innerHTML = tokens
						.map((t, i) => {
							const tag = t.flagship ? '★  ' : `#${t.rank ?? i}  `;
							return `<option value="${escapeHtml(t.mint)}" data-symbol="${escapeHtml(t.symbol)}">${tag}${escapeHtml(t.symbol)}  (${escapeHtml(shortAddr(t.mint))})</option>`;
						})
						.join('');
					// Keep the currently-charted token selected if it survived the refresh;
					// otherwise fall to the pinned flagship at the top.
					const keep = Array.from(sel.options).findIndex((o) => o.value === prevMint);
					sel.selectedIndex = keep >= 0 ? keep : 0;
					const first = tokens[sel.selectedIndex] || tokens[0];
					selectChartToken(first.mint, first.symbol);
				} catch {
					// Network error — the $THREE default is already charted; leave it.
				}
			}

			// Chart source bar: this desk's own candle chart, or any terminal the rest
			// of three.ws offers (DexScreener, Birdeye, GMGN, DEXTools, GeckoTerminal).
			// The native canvas stays in the DOM and is only hidden while a provider
			// is showing, because the fetch, overlay and hover code all address it by
			// id; its ResizeObserver redraws it the moment it is shown again.
			let chartSources = null;
			function mountChartSources(mint) {
				chartSources?.destroy();
				const nativeBlock = $('pd-chart-native');
				chartSources = mountSwitchableChart({
					host: $('pd-chart-switch'),
					mint,
					nativeViews: [
						{
							id: 'threews',
							label: 'three.ws',
							mount: () => {
								nativeBlock.hidden = false;
								return { destroy: () => (nativeBlock.hidden = true) };
							},
						},
					],
					classes: { tabs: 'pd-chart-sources', tab: 'pd-btn pd-btn-sm', active: 'is-primary' },
				});
			}

			async function fetchChartData(mint, symbol) {
				chart.mint = mint;
				chart.symbol = symbol;
				chart.spotUsd = null;
				const canvas = $('pd-market-chart');
				drawChartMessage(canvas, 'skeleton');
				$('pd-chart-meta').innerHTML =
					`<span class="pd-mono" style="color:var(--accent)">${escapeHtml(symbol || '')}</span> <span style="color:var(--ink-dim)">${escapeHtml(shortAddr(mint))}</span>`;
				const now = Math.floor(Date.now() / 1000);
				const from = now - 24 * 3600;
				try {
					const r = await fetch(
						`/api/pump/price-history?mint=${encodeURIComponent(mint)}&interval=15m&from=${from}&to=${now}`,
					);
					const d = await r.json().catch(() => ({}));
					if (!r.ok) {
						drawChartMessage(
							canvas,
							d.error_description || d.error || `Error ${r.status}`,
						);
						$('pd-chart-retry').hidden = false;
						return;
					}
					$('pd-chart-retry').hidden = true;
					chart.candles = d.data || [];
					if (!chart.candles.length) {
						drawChartMessage(canvas, 'No trades in the selected window');
					} else {
						drawMarketChart(canvas);
						const last = chart.candles[chart.candles.length - 1].c;
						$('pd-chart-meta').innerHTML +=
							` · <span style="color:var(--accent)">$${fmtPrice(last)}</span>`;
					}
					fetchSpotOverlay(mint);
				} catch (e) {
					drawChartMessage(canvas, e.message || 'load failed');
					$('pd-chart-retry').hidden = false;
				}
			}

			// Live PumpFun bonding-curve spot price, converted to USD via the cached
			// SOL price and overlaid as a dashed line. Silent no-op for non-PumpFun mints.
			async function fetchSpotOverlay(mint) {
				try {
					const r = await fetch(`/api/pump/curve?mint=${encodeURIComponent(mint)}`);
					if (!r.ok) return;
					const d = await r.json();
					const priceSol = Number(d.price?.priceSol);
					if (!isFinite(priceSol) || priceSol <= 0 || !state.solPrice) return;
					chart.spotUsd = priceSol * state.solPrice;
					if (chart.candles.length) drawMarketChart($('pd-market-chart'));
					$('pd-chart-meta').innerHTML +=
						` · <span style="color:var(--warn)">live ${priceSol.toFixed(9)} SOL</span>`;
				} catch {
					/* overlay optional */
				}
			}

			function drawMarketChart(canvas) {
				const candles = chart.candles;
				if (!candles.length) {
					drawChartMessage(canvas, 'No trades in the selected window');
					return;
				}
				const { ctx, w, h } = setupCanvas(canvas);
				ctx.clearRect(0, 0, w, h);
				const x0 = 56,
					x1 = w - 12,
					y0 = 10,
					y1 = h - 22;
				const tMin = candles[0].t,
					tMax = candles[candles.length - 1].t;
				let pMin = Infinity,
					pMax = -Infinity;
				for (const c of candles) {
					pMin = Math.min(pMin, c.l ?? c.c);
					pMax = Math.max(pMax, c.h ?? c.c);
				}
				if (chart.spotUsd != null) {
					pMin = Math.min(pMin, chart.spotUsd);
					pMax = Math.max(pMax, chart.spotUsd);
				}
				if (pMin === pMax) {
					pMin *= 0.99;
					pMax *= 1.01;
				}
				const padP = (pMax - pMin) * 0.08;
				pMin -= padP;
				pMax += padP;
				const xFor = (t) =>
					x0 + (tMax === tMin ? 0 : (t - tMin) / (tMax - tMin)) * (x1 - x0);
				const yFor = (p) => y1 - ((p - pMin) / (pMax - pMin)) * (y1 - y0);
				// Y grid + price ticks
				ctx.strokeStyle = 'rgba(255,255,255,0.06)';
				ctx.fillStyle = 'rgba(255,255,255,0.42)';
				ctx.font = '10px system-ui';
				ctx.lineWidth = 1;
				ctx.textAlign = 'right';
				ctx.textBaseline = 'middle';
				for (let i = 0; i <= 5; i++) {
					const p = pMin + ((pMax - pMin) * i) / 5;
					const y = yFor(p);
					ctx.beginPath();
					ctx.moveTo(x0, y);
					ctx.lineTo(x1, y);
					ctx.stroke();
					ctx.fillText('$' + fmtPrice(p), x0 - 6, y);
				}
				// X time ticks
				ctx.textAlign = 'center';
				ctx.textBaseline = 'top';
				const spanHours = (tMax - tMin) / 3600;
				for (let i = 0; i <= 6; i++) {
					const t = tMin + ((tMax - tMin) * i) / 6;
					const x = xFor(t);
					const dt = new Date(t * 1000);
					const label =
						spanHours <= 24
							? dt.toLocaleTimeString('en-US', {
									hour12: false,
									hour: '2-digit',
									minute: '2-digit',
								})
							: `${dt.getMonth() + 1}/${dt.getDate()}`;
					ctx.fillText(label, Math.max(x0 + 14, Math.min(x1 - 14, x)), y1 + 5);
				}
				// Price line + area
				ctx.strokeStyle = cssVar('--accent');
				ctx.lineWidth = 1.5;
				ctx.beginPath();
				candles.forEach((c, i) => {
					const x = xFor(c.t),
						y = yFor(c.c);
					i ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
				});
				ctx.stroke();
				ctx.lineTo(xFor(tMax), y1);
				ctx.lineTo(xFor(tMin), y1);
				ctx.closePath();
				ctx.fillStyle = 'rgba(255,255,255,0.05)';
				ctx.fill();
				// Spot overlay
				if (chart.spotUsd != null) {
					const y = yFor(chart.spotUsd);
					ctx.strokeStyle = cssVar('--warn');
					ctx.setLineDash([4, 3]);
					ctx.beginPath();
					ctx.moveTo(x0, y);
					ctx.lineTo(x1, y);
					ctx.stroke();
					ctx.setLineDash([]);
				}
				chart.geom = { x0, x1, y0, y1, tMin, tMax, pMin, pMax };
			}

			// mousemove fires far faster than the screen refreshes; a full chart
			// re-render per event pegs the main thread and makes the crosshair cursor
			// flicker. Coalesce to at most one redraw per animation frame.
			let _chartHoverRaf = 0;
			let _chartHoverX = 0;
			function onChartMove(e) {
				const canvas = $('pd-market-chart');
				const rect = canvas.getBoundingClientRect();
				_chartHoverX = e.clientX - rect.left;
				if (!_chartHoverRaf) _chartHoverRaf = requestAnimationFrame(drawChartCrosshair);
			}

			function drawChartCrosshair() {
				_chartHoverRaf = 0;
				const canvas = $('pd-market-chart');
				const tip = $('pd-chart-tooltip');
				const g = chart.geom;
				if (!g || !chart.candles.length) {
					tip.style.display = 'none';
					return;
				}
				const x = _chartHoverX;
				if (x < g.x0 || x > g.x1) {
					tip.style.display = 'none';
					return;
				}
				const frac = (x - g.x0) / (g.x1 - g.x0);
				const t = g.tMin + frac * (g.tMax - g.tMin);
				let nearest = chart.candles[0],
					best = Infinity;
				for (const c of chart.candles) {
					const dd = Math.abs(c.t - t);
					if (dd < best) {
						best = dd;
						nearest = c;
					}
				}
				const cx =
					g.x0 +
					(g.tMax === g.tMin ? 0 : (nearest.t - g.tMin) / (g.tMax - g.tMin)) *
						(g.x1 - g.x0);
				const cy = g.y1 - ((nearest.c - g.pMin) / (g.pMax - g.pMin)) * (g.y1 - g.y0);
				drawMarketChart(canvas);
				const ctx = canvas.getContext('2d');
				ctx.strokeStyle = 'rgba(255,255,255,0.4)';
				ctx.lineWidth = 1;
				ctx.setLineDash([3, 3]);
				ctx.beginPath();
				ctx.moveTo(cx, g.y0);
				ctx.lineTo(cx, g.y1);
				ctx.stroke();
				ctx.setLineDash([]);
				ctx.fillStyle = cssVar('--accent');
				ctx.beginPath();
				ctx.arc(cx, cy, 3, 0, Math.PI * 2);
				ctx.fill();
				const dt = new Date(nearest.t * 1000);
				tip.textContent = `${dt.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' })} · $${fmtPrice(nearest.c)}`;
				tip.style.left = cx + 'px';
				tip.style.top = cy + 'px';
				tip.style.display = 'block';
			}

			// ════════════════════════════════════════════════════════════
			//  API keys (Task 09)
			// ════════════════════════════════════════════════════════════
			async function loadApiKeys() {
				const tbody = $('pd-keys-table');
				tbody.innerHTML = '<tr><td colspan="7" class="pd-empty">Loading…</td></tr>';
				try {
					const r = await apiFetch('/api/api-keys');
					if (r.status === 401) {
						tbody.innerHTML =
							'<tr><td colspan="7" class="pd-empty">Sign in to manage keys. <a href="/login" style="color:var(--accent)">Sign in</a></td></tr>';
						$('pd-keys-count').textContent = '—';
						return;
					}
					if (r.status === 429) {
						tbody.innerHTML =
							'<tr><td colspan="7" class="pd-empty">Too many requests, try again shortly.</td></tr>';
						return;
					}
					if (!r.ok) {
						tbody.innerHTML = `<tr><td colspan="7" class="pd-empty">Error ${r.status}.</td></tr>`;
						return;
					}
					const { data } = await r.json();
					$('pd-keys-count').textContent = String(data.length);
					if (!data.length) {
						tbody.innerHTML =
							'<tr><td colspan="7" class="pd-empty">You haven\'t created any API keys yet.</td></tr>';
						return;
					}
					tbody.innerHTML = data
						.map(
							(k) => `<tr>
						<td>${escapeHtml(k.name)}</td>
						<td class="pd-mono">${escapeHtml(k.prefix)}…</td>
						<td class="pd-mono" style="font-size:0.74rem">${escapeHtml((k.scope || '').split(/\s+/).filter(Boolean).join(', '))}</td>
						<td class="pd-mono">${k.created_at ? new Date(k.created_at).toLocaleDateString() : '—'}</td>
						<td class="pd-mono">${k.last_used_at ? relTimeIso(k.last_used_at) : 'never'}</td>
						<td class="pd-mono">${k.expires_at ? new Date(k.expires_at).toLocaleDateString() : '—'}</td>
						<td><button class="pd-btn pd-btn-sm is-danger" type="button" data-revoke-key="${escapeHtml(k.id)}">Revoke</button></td>
					</tr>`,
						)
						.join('');
					tbody
						.querySelectorAll('[data-revoke-key]')
						.forEach((b) =>
							b.addEventListener('click', () => revokeApiKey(b.dataset.revokeKey)),
						);
				} catch (e) {
					tbody.innerHTML = `<tr><td colspan="7" class="pd-empty">Failed: ${escapeHtml(e.message || 'load failed')}</td></tr>`;
				}
			}
			async function createApiKey(e) {
				e.preventDefault();
				const name = $('pd-key-name').value.trim();
				if (!name) {
					toast('Key name is required', 'error');
					return;
				}
				const scopes = Array.from(document.querySelectorAll('.pd-key-scope:checked')).map(
					(c) => c.value,
				);
				if (!scopes.length) {
					toast('Select at least one scope', 'error');
					return;
				}
				const body = { name, scope: scopes.join(' ') };
				const expiryRaw = $('pd-key-expiry').value;
				if (expiryRaw) body.expires_at = new Date(expiryRaw).toISOString();
				const btn = $('pd-key-create');
				btn.disabled = true;
				try {
					const csrf = await getCsrfToken();
					const headers = { 'Content-Type': 'application/json' };
					if (csrf) headers['x-csrf-token'] = csrf;
					const r = await apiFetch('/api/api-keys', {
						method: 'POST',
						headers,
						body: JSON.stringify(body),
					});
					if (r.status === 429) {
						toast('Too many requests, try again shortly', 'error');
						return;
					}
					if (!r.ok) {
						const err = await r.json().catch(() => ({}));
						toast(
							err.error_description || err.error || `Create failed (${r.status})`,
							'error',
						);
						return;
					}
					const { data } = await r.json();
					$('pd-key-token').value = data.token;
					openModal('pd-key-modal');
				} catch (e2) {
					toast('Network error: ' + (e2.message || 'create failed'), 'error');
				} finally {
					btn.disabled = false;
				}
			}
			async function revokeApiKey(id) {
				if (!confirm('Revoke this API key? Apps using it will stop working immediately.'))
					return;
				try {
					const csrf = await getCsrfToken();
					const headers = {};
					if (csrf) headers['x-csrf-token'] = csrf;
					const r = await apiFetch('/api/api-keys/' + encodeURIComponent(id), {
						method: 'DELETE',
						headers,
					});
					if (!r.ok) {
						const err = await r.json().catch(() => ({}));
						toast(
							err.error_description || err.error || `Revoke failed (${r.status})`,
							'error',
						);
						return;
					}
					toast('Key revoked', 'success');
					loadApiKeys();
				} catch (e) {
					toast('Network error revoking key', 'error');
				}
			}

			// ── Boot ─────────────────────────────────────────────────────

			document.addEventListener('DOMContentLoaded', () => {
				$('pd-cfg-api-url').value = state.apiUrl;
				$('pd-cfg-ws-url').value = state.wsUrl;
				$('pd-cfg-api-key').value = state.apiKey;
				$('pd-cfg-rpc-url').value = state.rpcUrl;
				$('pd-api-endpoint-display').textContent = state.apiUrl;

				// Sidebar nav
				document.querySelectorAll('.pd-sidebar nav a').forEach((a) => {
					a.addEventListener('click', (e) => {
						e.preventDefault();
						navigateTo(a.dataset.page);
					});
				});

				// Deep links: honor #hash on load and when the URL is edited by hand.
				const hashPage = location.hash.slice(1);
				if (hashPage && hashPage !== state.currentPage && $('page-' + hashPage))
					navigateTo(hashPage);
				// /pump-dashboard?agent=<id> (from the launch-token modal) opens the
				// agent control panel directly, unless an explicit #hash overrides it.
				else if (state.agentId && $('page-animations')) navigateTo('animations');
				window.addEventListener('hashchange', () => {
					const page = location.hash.slice(1);
					if (page && page !== state.currentPage && $('page-' + page)) navigateTo(page);
				});

				// Filter buttons
				document.querySelectorAll('.pd-filter-btn').forEach((b) => {
					b.addEventListener('click', () => setFeedFilter(b.dataset.filter));
				});
				setFeedFilter(state.currentFilter);

				$('pd-feed-pause').addEventListener('change', (e) => {
					state.feedPaused = e.target.checked;
				});

				// Dashboard & live feed clears
				$('pd-clear-dash-feed').addEventListener('click', () =>
					clearFeed('pd-dashboard-feed'),
				);
				$('pd-clear-live-feed').addEventListener('click', () => clearFeed('pd-live-feed'));
				$('pd-clear-alert-feed').addEventListener('click', () =>
					clearFeed('pd-alert-feed'),
				);

				// Watches
				$('pd-add-watch-btn').addEventListener('click', () => {
					// Opening the form against an origin with no watches API would only
					// hand the user a 404 on submit. Send them where the fix lives.
					if (state.watchesSupported === false) {
						toast('Point the API URL at a PumpKit deployment to create watches', 'error');
						navigateTo('config');
						$('pd-cfg-api-url')?.focus();
						return;
					}
					openModal('pd-add-watch-modal');
				});
				$('pd-refresh-watches').addEventListener('click', refreshWatches);
				$('pd-cancel-watch').addEventListener('click', () =>
					closeModal('pd-add-watch-modal'),
				);
				$('pd-create-watch').addEventListener('click', createWatch);

				// Claims
				$('pd-refresh-claims').addEventListener('click', refreshClaims);
				$('pd-export-claims').addEventListener('click', exportClaims);

				// Alerts (server-persisted rules)
				$('pd-rule-save').addEventListener('click', saveRule);
				$('pd-rule-cancel').addEventListener('click', resetRuleForm);
				$('pd-rules-refresh').addEventListener('click', loadAlertRules);
				$('pd-rule-kind').addEventListener('change', updateRuleFormFields);
				$('pd-rule-scope').addEventListener('change', updateRuleFormFields);
				$('pd-rules-list').addEventListener('click', onRulesListClick);
				$('pd-rules-list').addEventListener('change', onRulesListChange);

				// Scanner
				$('pd-scan-token').addEventListener('click', scanToken);

				// Quotes
				$('pd-get-buy-quote').addEventListener('click', getBuyQuote);
				$('pd-get-sell-quote').addEventListener('click', getSellQuote);

				// Vanity
				$('pd-vanity-start').addEventListener('click', startVanity);
				$('pd-vanity-stop').addEventListener('click', stopVanity);

				// Animations + TTS (Task 11)
				$('pd-speak-btn').addEventListener('click', () => agentAction('speak'));
				$('pd-speak-stop').addEventListener('click', stopSpeak);
				$('pd-play-anim').addEventListener('click', playAnimation);
				document.querySelectorAll('[data-agent-action]').forEach((b) => {
					b.addEventListener('click', () => agentAction(b.dataset.agentAction));
				});
				window.addEventListener('message', handleAgentMessage);

				// Config (Task 10)
				$('pd-save-config').addEventListener('click', saveConfig);

				// Wallet snapshot (Task 02) — connect via src/wallet.js, react to events.
				initWalletButton();
				window.addEventListener('wallet:changed', (e) =>
					onWalletChanged(e.detail?.address || null),
				);
				$('connect-wallet-btn')?.addEventListener('click', () => {
					const holdings = $('pd-wallet-holdings');
					if (holdings && !getConnectedWalletAddress()) {
						$('pd-wallet-empty').hidden = true;
						holdings.hidden = false;
						holdings.innerHTML =
							'<div style="font-size:0.85rem;color:var(--ink-dim)">Connecting…</div>';
					}
				});
				$('pd-wallet-disconnect').addEventListener('click', disconnectWallet);

				// Market chart (Tasks 03 + 04)
				$('pd-chart-token').addEventListener('change', (e) => {
					const opt = e.target.selectedOptions[0];
					if (!opt || !opt.value) return;
					document.dispatchEvent(
						new CustomEvent('chart:tokenChange', {
							detail: { mint: opt.value, symbol: opt.dataset.symbol || '' },
						}),
					);
				});
				$('pd-chart-retry').addEventListener('click', () => {
					if (chart.mint) fetchChartData(chart.mint, chart.symbol);
					else loadTrendingTokens();
				});
				document.addEventListener('chart:tokenChange', (e) => {
					fetchChartData(e.detail.mint, e.detail.symbol);
					mountChartSources(e.detail.mint);
				});
				const marketCanvas = $('pd-market-chart');
				marketCanvas.addEventListener('mousemove', onChartMove);
				marketCanvas.addEventListener('mouseleave', () => {
					if (_chartHoverRaf) {
						cancelAnimationFrame(_chartHoverRaf);
						_chartHoverRaf = 0;
					}
					$('pd-chart-tooltip').style.display = 'none';
				});
				let _chartResizeRaf = 0;
				new ResizeObserver(() => {
					cancelAnimationFrame(_chartResizeRaf);
					_chartResizeRaf = requestAnimationFrame(() => {
						if (chart.candles.length) drawMarketChart(marketCanvas);
					});
				}).observe(marketCanvas);

				// API keys (Task 09)
				$('pd-key-create-form').addEventListener('submit', createApiKey);
				$('pd-key-copy').addEventListener('click', async () => {
					try {
						await navigator.clipboard.writeText($('pd-key-token').value);
						toast('Token copied', 'success');
					} catch {}
				});
				$('pd-key-done').addEventListener('click', () => {
					closeModal('pd-key-modal');
					$('pd-key-token').value = '';
					loadApiKeys();
				});

				// Modal dismissal (Escape + backdrop click), wired once
				initModalDismiss();

				// Boot the data flows
				connectApi();
				connectWebSocket();
				preloadChannelFeed();
				refreshNetworkStats();
				loadFeaturedAgent();
				loadTrendingTokens();
				pollMonitorStats();
				runConfigProbes();
				state.networkInterval = setInterval(refreshNetworkStats, 30000);
				state.monitorInterval = setInterval(pollMonitorStats, 10000);
				setInterval(updateUptime, 1000);
			});
		</script>

		<script>
		(function() {
			const TIER_META = {
				prime:   { color: '#c084fc', bg: 'rgba(192,132,252,.14)', label: 'PRIME' },
				strong:  { color: '#34d399', bg: 'rgba(52,211,153,.12)',  label: 'STRONG' },
				lean:    { color: '#fbbf24', bg: 'rgba(251,191,36,.12)',  label: 'LEAN' },
				watch:   { color: '#94a3b8', bg: 'rgba(148,163,184,.1)', label: 'WATCH' },
				avoid:   { color: '#f87171', bg: 'rgba(248,113,113,.12)', label: 'AVOID' },
			};
			const PILLAR_COLORS = { pedigree: '#5fe3ff', structure: '#34d399', narrative: '#a07bff', momentum: '#fbbf24' };
			const esc = s => String(s ?? '').replace(/[<>&"]/g, c => ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]));

			function renderOracleFeed(coins) {
				const el = document.getElementById('pd-oracle-feed');
				if (!el) return;
				if (!coins || coins.length === 0) {
					el.innerHTML = `<div class="pd-oracle-empty">No high-conviction coins right now — <a href="/oracle">explore Oracle →</a></div>`;
					return;
				}
				el.innerHTML = coins.slice(0, 5).map(c => {
					const cv = c.conviction || {};
					const tier = cv.tier || 'watch';
					const meta = TIER_META[tier] || TIER_META.watch;
					const score = Math.round(Number(cv.score ?? 0));
					const pillars = cv.pillars || {};
					const pillarHtml = ['pedigree', 'structure', 'narrative', 'momentum'].map(k => {
						const v = Math.round(Number(pillars[k] ?? 0));
						return `<div class="pd-oracle-bar" title="${k}: ${v}"><div class="pd-oracle-bar-fill" style="width:${v}%;background:${PILLAR_COLORS[k]}"></div></div>`;
					}).join('');
					const sym = esc((c.symbol || '').toUpperCase() || (c.mint || '').slice(0, 6));
					const name = esc(c.name || '');
					return `<a class="pd-oracle-item" href="/oracle/coin/${encodeURIComponent(c.mint)}" target="_blank" rel="noopener">
						<div class="pd-oracle-score-col" style="color:${meta.color}">
							<span class="pd-oracle-score-num">${score}</span>
							<span class="pd-oracle-score-label">score</span>
						</div>
						<div class="pd-oracle-info">
							<div class="pd-oracle-sym">$${sym}</div>
							${name ? `<div class="pd-oracle-name">${name}</div>` : ''}
							<div class="pd-oracle-pillars">${pillarHtml}</div>
						</div>
						<span class="pd-oracle-tier-badge" style="color:${meta.color};background:${meta.bg};border-color:${meta.color}40">${meta.label}</span>
					</a>`;
				}).join('');
			}

			async function loadOracleFeed() {
				try {
					const r = await fetch('/api/oracle/feed?network=mainnet&limit=5&min_score=60');
					if (!r.ok) throw new Error();
					const d = await r.json();
					renderOracleFeed(d.coins || []);
				} catch {
					const el = document.getElementById('pd-oracle-feed');
					if (el) el.innerHTML = `<div class="pd-oracle-empty"><a href="/oracle">Open Oracle →</a></div>`;
				}
			}

			document.addEventListener('DOMContentLoaded', () => {
				loadOracleFeed();
				setInterval(loadOracleFeed, 90_000);

				// Oracle stats strip
				fetch('/api/oracle/stats').then(r => r.ok ? r.json() : null).then(d => {
					if (!d) return;
					const set = (id, v) => { const e = document.getElementById(id); if (e) e.textContent = v; };
					const fmt = n => n >= 1e3 ? (n/1e3).toFixed(1)+'K' : String(n||0);
					set('pds-agents', fmt(d.agents_armed));
					set('pds-scored', fmt(d.scored_24h));
					set('pds-winrate', d.win_rate != null ? d.win_rate+'%' : '—');
					set('pds-open', fmt(d.open_actions));
					set('pds-ath', d.best_ath != null ? d.best_ath.toFixed(1)+'×' : '—');
				}).catch(()=>{});
			});
		})();
		</script>

		<script src="/footer.js" defer></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>