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.

111 KB
Raw Blame
// Forge — text / image / multi-view → 3D generator (browser client).
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from '../shared/state-kit.js';
import { showSharePanel } from '../shared/share.js';
import { stampGlbAttribution } from '../shared/glb-attribution.js';
import {
	primeTierPass,
	attachTierPass,
	getTierPass,
	getAccess,
	onGate,
	trackUpgradeConverted,
} from '../three-access.js';
import { renderLock, lockStateFromAccess } from '../three-lock.js';
import { payForHighGeneration } from './forge-pay.js';
import { initWalletButton, getConnectedWalletAddress } from '../wallet.js';
import { openSketchCanvas } from './sketch-canvas.js';
import { mountPromptDictation } from '../voice/prompt-dictation.js';
import { showToast } from '../ui-helpers.js';
import { resolveDevR2Url } from '../shared/dev-r2-proxy.js';
import { coldStartLabel } from '../shared/forge-frames.js';
import { initForgeDestinationPicker, storedForgeDestination } from '../shared/forge-destination-picker.js';
ensureStateKitStyles();
//
// Drives /api/forge. Three paths share one polling loop:
//   • Text → 3D — POST a prompt; FLUX paints a reference image, then TRELLIS
//     reconstructs the mesh.
//   • Image / multi-view → 3D — the user adds 1–4 photos of one object from
//     different angles. Each photo is uploaded straight to object storage via a
//     presigned URL (/api/forge-upload), then their public URLs are POSTed as
//     image_urls. With >1 view the backend fuses them (multi-view conditioning)
//     and reports how many views it used + which backend handled it.
//   • Sketch → 3D — one drawing + a required prompt naming what it depicts,
//     generated by the self-host TripoSG scribble engine (path: 'sketch').
//     The mode tab only appears when the catalog reports that engine live.
//
// State transitions are driven by real API responses; the only timer is the
// honest elapsed counter. Nothing fakes progress.

const POLL_INTERVAL_MS = 2500;
// Ceiling for a single reconstruction run. Max-tier texture bakes legitimately
// run past 10 minutes at full quality; the ceiling must sit above the slowest
// real generation or the client abandons jobs the server finishes. Queue wait
// does not count against this window (see pollUntilDone).
const MAX_POLL_MS = 12 * 60 * 1000;
const MAX_VIEWS = 4;
const VIEW_LABELS = ['Front', 'Back', 'Left', 'Right'];
const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);

const els = {
	form: document.getElementById('composer'),
	prompt: document.getElementById('prompt'),
	aspect: document.getElementById('aspect'),
	generate: document.getElementById('generate'),
	generateLabel: document.getElementById('generate-label'),
	examples: document.getElementById('examples'),
	stage: document.getElementById('stage'),
	modeSwitch: document.getElementById('mode-switch'),
	textPane: document.getElementById('text-pane'),
	imagePane: document.getElementById('image-pane'),
	viewsGrid: document.getElementById('views-grid'),
	fileInput: document.getElementById('view-file-input'),
	imagePrompt: document.getElementById('image-prompt'),
	sketchPane: document.getElementById('sketch-pane'),
	sketchGrid: document.getElementById('sketch-grid'),
	sketchFileInput: document.getElementById('sketch-file-input'),
	sketchPrompt: document.getElementById('sketch-prompt'),
	drawViewBtn: document.getElementById('draw-view-btn'),
	drawSketchBtn: document.getElementById('draw-sketch-btn'),
	promptDictateSlot: document.getElementById('prompt-dictate-slot'),
	imagePromptDictateSlot: document.getElementById('image-prompt-dictate-slot'),
	sketchPromptDictateSlot: document.getElementById('sketch-prompt-dictate-slot'),
	states: {
		empty: document.getElementById('state-empty'),
		generating: document.getElementById('state-generating'),
		result: document.getElementById('state-result'),
		error: document.getElementById('state-error'),
		unconfigured: document.getElementById('state-unconfigured'),
	},
	genPreview: document.getElementById('gen-preview'),
	genMeta: document.getElementById('gen-meta'),
	genProgress: document.getElementById('gen-progress'),
	genProgressFill: document.getElementById('gen-progress-fill'),
	steps: {
		image: document.getElementById('step-image'),
		mesh: document.getElementById('step-mesh'),
		finish: document.getElementById('step-finish'),
	},
	cancel: document.getElementById('cancel'),
	viewer: document.getElementById('viewer'),
	viewerShell: document.getElementById('viewer-shell'),
	cinema: document.getElementById('cinema'),
	resultLabel: document.getElementById('result-label'),
	resultViews: document.getElementById('result-views'),
	verdict: document.getElementById('verdict'),
	download: document.getElementById('download'),
	again: document.getElementById('again'),
	refine: document.getElementById('refine'),
	refineLabel: document.getElementById('refine-label'),
	retry: document.getElementById('retry'),
	errorLanes: document.getElementById('error-lanes'),
	viewsCounter: document.getElementById('views-counter'),
	viewsCounterText: document.getElementById('views-counter-text'),
	viewsPips: document.getElementById('views-pips'),
	sketchReqTag: document.getElementById('sketch-req-tag'),
	generateAnyway: document.getElementById('generate-anyway'),
	refineLocally: document.getElementById('refine-locally'),
	errorMessage: document.getElementById('error-message'),
	forgeShareBtn: document.getElementById('forge-share-btn'),
	segmentBtn: document.getElementById('forge-segment-btn'),
	openInComposer: document.getElementById('open-in-composer'),
	categoryPicker: document.getElementById('forge-category-picker'),
	destinationPicker: document.getElementById('forge-destination-picker'),
	destinationStatus: document.getElementById('forge-destination-status'),
	savedChip: document.getElementById('result-saved'),
	creations: document.getElementById('creations'),
	creationsGrid: document.getElementById('creations-grid'),
	creationsCount: document.getElementById('creations-count'),
	// Quality tier + generation engine + BYOK key.
	tier: document.getElementById('tier'),
	// Persistent inline hint under the Quality row — advertises that High is a
	// $THREE holder feature (toggled locked/unlocked by the live access read).
	holderNote: document.getElementById('fq-holder-note'),
	engine: document.getElementById('engine'),
	byokRow: document.getElementById('byok-row'),
	byokLabel: document.getElementById('byok-label'),
	byokHint: document.getElementById('byok-hint'),
	providerKey: document.getElementById('provider-key'),
	estimate: document.getElementById('estimate'),
	// Holder free-quota perk line + the Forge-local wallet-connect chip (Part A).
	perkRow: document.getElementById('forge-perk-row'),
	perkLine: document.getElementById('forge-perk-line'),
	connectBtn: document.getElementById('connect-wallet-btn'),
};

let aspectRatio = '1:1';
let elapsedTimer = null;
let pollAbort = false;
let mode = 'text'; // 'text' | 'image' | 'sketch' — input mode (prompt vs photos vs drawing)
let lastJob = null; // { prompt, imageUrls } — for retry
// Automatic engine hops taken for the current submission (lane_failed → switch
// to the first suggested backup and re-run). Budget of 1 per user submit; the
// server's own poll-time failover already walked the async lanes before this.
let autoLaneHops = 0;
let currentCreationId = null;
// The rows currently rendered in "Your creations", kept so a delete can drop
// one card in place (count, empty state) without a refetch.
let galleryCreations = [];
// The quality tier the on-screen result was produced at — drives the "Refine"
// affordance, which re-runs the same job exactly one tier higher.
let currentResultTier = null;
// The GLB currently shown in the viewer (set on every result). Lets the
// rate-limit state know a model exists to refine locally as a fallback.
let lastShownGlb = '';

// Quality tiers, lowest → highest. Refine walks one step up this ladder.
const TIER_ORDER = ['draft', 'standard', 'high'];
const TIER_LABELS = { draft: 'Draft', standard: 'Standard', high: 'High' };
function nextTierAfter(tier) {
	const i = TIER_ORDER.indexOf(tier);
	return i >= 0 && i < TIER_ORDER.length - 1 ? TIER_ORDER[i + 1] : null;
}

// Generation route + quality. `genPath` is the task's image|geometry axis;
// `genBackend` names the provider; both come from the selected engine button.
// The catalog (tiers + backends + cost/time matrix) is fetched once on load.
let catalog = null;
// Live backend health (/api/forge?health) — probed upstream auth/quota, not
// just env presence. Null until the probe returns; the buttons render
// optimistically from the catalog and tighten when health lands.
let health = null;
let selectedTier = 'standard';
let selectedEngine = {
	id: 'trellis',
	path: 'image',
	backend: 'trellis',
	byok: null,
	polyControl: false,
};
// Once the user deliberately picks an engine we stop auto-selecting the
// catalog's per-tier default (e.g. the free NVIDIA lane on draft) under them.
let userPickedEngine = false;
// BYOK key held only in memory for this session — sent per request, never stored
// by the page. Signed-in users can instead save it server-side in Account.
let providerKey = '';

// Cinema mode — distraction-free fullscreen turntable for recording/sharing.
// Toggled by the result-bar button or F; Esc always exits. Rotation slows so
// the loop reads as deliberate, not busy.
let cinemaOn = false;
function setCinema(on) {
	if (!els.cinema || on === cinemaOn) return;
	cinemaOn = on;
	els.states.result.classList.toggle('is-cinema', on);
	document.body.classList.toggle('forge-cinema', on);
	els.cinema.setAttribute('aria-pressed', String(on));
	els.viewer.setAttribute('rotation-per-second', on ? '10deg' : '18deg');
}

// Inline key glyph appended to BYOK engine buttons. Stroke = currentColor so it
// tracks the button's text color through hover/selected/disabled states.
const ENGINE_KEY_SVG =
	'<svg class="eng-key" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="7.5" cy="15.5" r="4.5"/><path d="M10.7 12.3 21 2"/><path d="m15 7 3 3"/><path d="m18 4 3 3"/></svg>';

// Inline "FREE" pill appended to zero-cost engine buttons (catalog `free:true`).
// The free lanes are named by engine like every other button; this pill — not
// the label — is what marks them free, so two free lanes never both read "Free".
const ENGINE_FREE_PILL = '<span class="eng-free" aria-hidden="true">FREE</span>';

// Short engine labels for the picker buttons, keyed by backend id. Free lanes
// carry the FREE pill above, so they are labelled by engine name like the rest.
const ENGINE_LABELS = {
	nvidia: 'NVIDIA',
	huggingface: 'Hunyuan3D',
	trellis: 'Fast',
	trellis_selfhost: 'TRELLIS',
	meshy: 'Meshy',
	tripo: 'Tripo',
	rodin: 'Rodin',
	stability: 'Stability',
	replicate_byok: 'Replicate',
	hunyuan3d: 'Hunyuan3D',
	triposg: 'TripoSG',
};

// Where to mint a key per BYOK provider, keyed by the backend's `byok` name.
// Mirrors the canonical registry in api/_lib/provider-keys.js (BYOK_PROVIDERS)
// and the Account key manager (dashboard-next/pages/account.js) — keep in sync.
const KEY_HINTS = {
	meshy: { label: 'Meshy AI', url: 'https://www.meshy.ai/settings/api' },
	tripo: { label: 'Tripo AI', url: 'https://platform.tripo3d.ai/api-keys' },
	rodin: { label: 'Rodin (Hyper3D)', url: 'https://developer.hyper3d.ai' },
	stability: { label: 'Stability AI', url: 'https://platform.stability.ai/account/keys' },
	replicate: { label: 'Replicate', url: 'https://replicate.com/account/api-tokens' },
};

// One entry per reference-view slot. `state` drives the slot's rendered region;
// `url` is the durable public URL (what we send); `objectUrl` is the local
// preview blob, revoked when the slot is cleared.
const slots = VIEW_LABELS.map(() => ({
	state: 'empty',
	url: null,
	objectUrl: null,
	errorMsg: '',
}));

// File picker target: the slot index the picker was opened for, or null to fill
// from the first free slot.
let pickerTarget = null;

// Sketch mode input — one drawing, same lifecycle as a view slot.
const sketch = { state: 'empty', url: null, objectUrl: null, errorMsg: '' };

// Stable anonymous handle for this browser. /forge has no login, so durable
// creations + the gallery are scoped to this id (hashed server-side). Sent on
// every request via the x-forge-client header.
const CLIENT_ID = (() => {
	const KEY = 'forge:cid';
	try {
		let id = localStorage.getItem(KEY);
		if (!id) {
			id =
				crypto?.randomUUID?.() ||
				`c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
			localStorage.setItem(KEY, id);
		}
		return id;
	} catch {
		// Private mode / storage blocked — fall back to an ephemeral per-load id.
		return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
	}
})();

const CLIENT_HEADERS = { 'x-forge-client': CLIENT_ID };

const REDUCED_MOTION =
	typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;

function showState(name) {
	for (const [key, node] of Object.entries(els.states)) {
		node.classList.toggle('is-hidden', key !== name);
	}
	// Leaving the result state always leaves cinema mode with it.
	if (name !== 'result' && cinemaOn) setCinema(false);
}

function setStep(step, state) {
	if (els.steps[step]) els.steps[step].dataset.state = state;
	// The scanline sweep runs exactly while the mesh step is live.
	if (step === 'mesh') els.genPreview.classList.toggle('is-reconstructing', state === 'active');
}

function setStepLabel(step, text) {
	const node = els.steps[step]?.querySelector('span:last-child');
	if (node) node.textContent = text;
}

// The typical end-to-end time for the current engine+tier, straight from the
// catalog's real estimate matrix (estimateEtaSeconds). Null when no catalog or
// estimate exists — the meter then runs indeterminate rather than inventing a
// duration.
function currentEtaSeconds() {
	if (!catalog) return null;
	const backend = catalog.backends?.find((b) => b.id === selectedEngine.backend);
	const est = (backend?.estimates?.[selectedEngine.path] || []).find(
		(e) => e.tier === selectedTier,
	);
	return Number(est?.eta_seconds) > 0 ? Number(est.eta_seconds) : null;
}

// Map real elapsed seconds onto an honest fill fraction. The curve approaches
// 1 asymptotically and is capped below it, so the bar can never reach full on
// time alone — only a real finished GLB sets it to 100% (see markDone). At
// elapsed = typical the fill sits ~0.78; it keeps creeping past that but never
// claims completion.
function honestFill(elapsedS, typicalS) {
	const frac = 1 - Math.exp(-elapsedS / (typicalS * 0.66));
	return Math.min(frac, 0.95);
}

function setProgress(pct) {
	if (!els.genProgressFill || !els.genProgress) return;
	const clamped = Math.max(0, Math.min(100, pct));
	els.genProgressFill.style.width = `${clamped}%`;
	els.genProgress.setAttribute('aria-valuenow', String(Math.round(clamped)));
}

function startElapsed() {
	const started = performance.now();
	stopElapsed();
	const typical = currentEtaSeconds();
	// Reset the meter to a clean running state for this job.
	if (els.genProgress) {
		els.genProgress.dataset.done = 'false';
		els.genProgress.dataset.over = 'false';
		els.genProgress.dataset.indeterminate = typical ? 'false' : 'true';
	}
	setProgress(0);
	const tick = () => {
		const s = Math.floor((performance.now() - started) / 1000);
		if (typical) {
			const over = s > typical;
			setProgress(honestFill(s, typical) * 100);
			if (els.genProgress) els.genProgress.dataset.over = String(over);
			els.genMeta.innerHTML = over
				? `Elapsed <strong>${s}s</strong> · longer than usual, still working`
				: `Elapsed <strong>${s}s</strong> · ~${Math.max(1, typical - s)}s left`;
		} else {
			// Unknown duration — the bar travels (indeterminate) and we report only
			// the honest elapsed count.
			els.genMeta.innerHTML = `Elapsed <strong>${s}s</strong>`;
		}
	};
	tick();
	elapsedTimer = window.setInterval(tick, 1000);
}

// Snap the meter to a finished, successful state — the only path to 100%.
function markProgressDone() {
	if (!els.genProgress) return;
	els.genProgress.dataset.indeterminate = 'false';
	els.genProgress.dataset.over = 'false';
	els.genProgress.dataset.done = 'true';
	setProgress(100);
}

function stopElapsed() {
	if (elapsedTimer) {
		window.clearInterval(elapsedTimer);
		elapsedTimer = null;
	}
}

function setBusy(busy) {
	els.generate.dataset.busy = busy ? '1' : '0';
	els.generate.disabled = busy;
	els.generateLabel.textContent = busy ? 'Forging…' : 'Generate';
	// When returning to idle, re-assert the High-tier $THREE gate (if active) so a
	// finished/cancelled job doesn't leave the Generate button enabled for a tier
	// the user can't use.
	if (!busy) applyHighGate();
}

function sleep(ms) {
	return new Promise((resolve) => setTimeout(resolve, ms));
}

// Mode switching --------------------------------------------------------------

function setMode(next) {
	if (next !== 'text' && next !== 'image' && next !== 'sketch') return;
	mode = next;
	els.textPane.classList.toggle('is-hidden', mode !== 'text');
	els.imagePane.classList.toggle('is-hidden', mode !== 'image');
	els.sketchPane?.classList.toggle('is-hidden', mode !== 'sketch');
	els.examples.classList.toggle('is-hidden', mode !== 'text');
	for (const b of els.modeSwitch.querySelectorAll('button')) {
		b.setAttribute('aria-selected', String(b.dataset.mode === mode));
	}
	// Sketch serves through its own engine set (TripoSG) — rebuild the selector
	// so each mode only offers engines that can actually take its input.
	if (catalog) buildEngineButtons();
	updateAspectVisibility();
	if (mode === 'text') els.prompt.focus();
	if (mode === 'sketch' && sketch.state === 'empty') sketchSlotEl()?.focus();
}

// Aspect ratio only shapes the synthesized reference image — irrelevant when
// the user supplies their own photos OR uses the geometry-first path (which
// never paints an intermediate image).
function updateAspectVisibility() {
	if (!els.aspect) return;
	const relevant = mode === 'text' && selectedEngine.path === 'image';
	els.aspect.classList.toggle('is-hidden', !relevant);
}

// Quality tier + engine ------------------------------------------------------

// Fetch the tier/backend/cost catalog once, then build the engine selector from
// the backends that are live (platform-configured) or BYOK (always selectable).
async function loadCatalog() {
	const qualityEl = els.engine?.closest('#forge-quality');
	const errorEl = document.getElementById('forge-quality-error');
	// A transport failure and a served-but-catalog-less response mean different
	// things to the user: the first is retryable and worth surfacing, the second
	// is a deploy that simply has no picker to show.
	let reachable = false;
	try {
		const res = await fetch('/api/forge?catalog=1', { headers: CLIENT_HEADERS });
		reachable = res.ok;
		catalog = reachable ? await res.json().catch(() => null) : null;
	} catch {
		catalog = null;
	}
	if (!catalog || !Array.isArray(catalog.backends)) {
		qualityEl?.classList.add('is-hidden');
		// A served response without a backends array is an older deploy with
		// nothing to pick, so it stays silent as before.
		if (errorEl && !reachable) showCatalogError(errorEl);
		return;
	}
	if (errorEl) {
		errorEl.innerHTML = '';
		errorEl.classList.add('is-hidden');
		errorEl.removeAttribute('aria-busy');
	}
	qualityEl?.classList.remove('is-hidden');
	buildEngineButtons();
	selectTier(selectedTier);
	revealSketchMode();
	loadHealth();
}

// Render the retryable notice that replaces the quality/engine controls when the
// catalog could not be reached.
function showCatalogError(errorEl) {
	errorEl.innerHTML = errorStateHTML({
		title: "Couldn't load the engine list",
		body: 'Quality and engine options are unavailable right now. Generation still works on the default free engine, or retry to get the full picker back.',
	});
	errorEl.classList.remove('is-hidden');
	errorEl.removeAttribute('aria-busy');
	errorEl.querySelector('[data-sk-retry]')?.addEventListener('click', () => {
		// Hold the block open with a real pending state instead of clearing it.
		// The catalog round trip takes seconds on a cold or busy backend, and
		// blanking the notice on click left an unexplained gap where the picker
		// belongs until loadCatalog resolved.
		const btn = errorEl.querySelector('[data-sk-retry]');
		if (btn) {
			btn.disabled = true;
			btn.textContent = 'Checking again';
		}
		errorEl.setAttribute('aria-busy', 'true');
		loadCatalog();
	});
}

// Sketch→3D needs the self-host TripoSG worker — the tab stays hidden unless
// the catalog reports that engine configured, so there is no dead mode on
// deployments without it.
function revealSketchMode() {
	const tab = els.modeSwitch?.querySelector('button[data-mode="sketch"]');
	if (!tab) return;
	const live = catalog.backends.some((b) => b.paths?.includes('sketch') && b.configured);
	tab.hidden = !live;
	if (live) buildSketchSlot();
}

// Live-probe the backends in the background, then tighten the engine buttons:
// a lane whose upstream is down gets disabled with the real reason instead of
// failing after the user has already typed a prompt and clicked Generate.
// On failure, retries twice (at 30s then 60s) before giving up.
let healthRetryCount = 0;
async function loadHealth() {
	try {
		const res = await fetch('/api/forge?health=1', { headers: CLIENT_HEADERS });
		const body = await res.json().catch(() => null);
		health = body && body.backends ? body : null;
	} catch {
		health = null;
	}
	if (health) {
		healthRetryCount = 0;
		updateEngineAvailability();
	} else if (healthRetryCount < 2) {
		healthRetryCount += 1;
		setTimeout(loadHealth, healthRetryCount * 30_000);
	}
}

function buildEngineButtons() {
	if (!els.engine) return;
	// Each mode offers only the engines that take its input: sketch mode shows
	// the sketch-path engines (TripoSG); text/photo modes hide sketch-only ones.
	const usable = catalog.backends.filter((b) => {
		if (!(b.configured || b.byok)) return false;
		const sketchOnly = Array.isArray(b.paths) && b.paths.every((p) => p === 'sketch');
		return mode === 'sketch' ? b.paths.includes('sketch') : !sketchOnly;
	});
	els.engine.innerHTML = '';
	for (const b of usable) {
		// Each backend exposes the geometry-first path when it supports it; the
		// image-intermediate engines (TRELLIS, Hunyuan3D) keep the image path.
		const path =
			mode === 'sketch' ? 'sketch' : b.paths.includes('geometry') ? 'geometry' : 'image';
		const btn = document.createElement('button');
		btn.type = 'button';
		btn.dataset.engine = b.id;
		btn.dataset.path = path;
		btn.dataset.backend = b.id;
		btn.dataset.byok = b.byok || '';
		btn.dataset.poly = String(Boolean(b.poly_control));
		// Text-only engines (the free NVIDIA TRELLIS preview) can't take photos;
		// updateEngineAvailability() disables them while reference views are set.
		btn.dataset.userimages = String(b.user_images !== false);
		// BYOK engines carry a small key glyph so the picker shows at a glance
		// which lanes run on the user's own API key vs the free/included ones.
		const short = ENGINE_LABELS[b.id] || b.label;
		btn.innerHTML = `<span class="eng-label">${short}</span> ${b.free ? ENGINE_FREE_PILL : ''}${b.byok ? ENGINE_KEY_SVG : ''}`;
		const keyNote = b.byok ? ` · uses your own ${KEY_HINTS[b.byok]?.label || b.byok} key` : '';
		const freeNote = b.free ? ' · free, no API key' : '';
		btn.title = `${b.label} — ${b.blurb}${freeNote}${keyNote}`;
		// aria-label survives the dynamic title rewrites in updateEngineAvailability.
		btn.setAttribute('aria-label', `${short}${freeNote}${keyNote}`);
		btn.setAttribute('aria-pressed', String(b.id === selectedEngine.backend));
		els.engine.appendChild(btn);
	}
	// If the previously-selected engine isn't usable, fall back to the first.
	if (!usable.some((b) => b.id === selectedEngine.backend)) {
		const first = els.engine.querySelector('button');
		if (first) selectEngine(first, true);
	}
	updateEngineAvailability();
}

// Keep the engine buttons honest about the current input mode, and keep the
// selection on the catalog's per-tier default until the user picks one.
//   • With reference photos attached, text-only engines are disabled (the free
//     NVIDIA TRELLIS preview rejects user images) and a selected one bounces to
//     the default photo engine.
//   • With no photos and no explicit user choice, the tier's default engine is
//     applied — which is what routes draft prompts onto the free lane.
function updateEngineAvailability() {
	if (!els.engine || !catalog) return;
	const hasPhotos = slots.some((s) => s.state === 'uploaded' || s.state === 'uploading');
	let bounceTo = null;
	for (const btn of els.engine.querySelectorAll('button')) {
		const textOnly = btn.dataset.userimages === 'false';
		const b = catalog.backends?.find((x) => x.id === btn.dataset.backend);
		// Live health beats the catalog's env-presence flag: a lane whose
		// upstream auth/billing probe failed is disabled with the real reason.
		const lane = health?.backends?.[btn.dataset.backend];
		const laneDown = lane && (lane.status === 'down' || lane.status === 'unconfigured');
		const laneBusy = lane && lane.status === 'degraded';
		const blocked = (textOnly && hasPhotos) || laneDown;
		btn.disabled = blocked;
		btn.setAttribute('aria-disabled', String(blocked));
		btn.dataset.health = lane ? lane.status : '';
		if (laneDown) {
			btn.title = `${b?.label || btn.dataset.backend} — temporarily unavailable: ${lane.message}`;
		} else if (blocked) {
			btn.title =
				'This engine generates from text prompts only — clear the reference views to use it.';
		} else if (b) {
			btn.title = laneBusy
				? `${b.label} — busy right now: ${lane.message}`
				: `${b.label} — ${b.blurb}`;
		}
		if (blocked && btn.dataset.backend === selectedEngine.backend) bounceTo = true;
	}
	const defaultId =
		catalog.default_backend_for_tier?.[selectedTier]?.[selectedEngine.path] ?? null;
	if (bounceTo) {
		// Forced move: the selected engine can't serve photos. Prefer the standing
		// photo default, else the first enabled button.
		const fallbackId = catalog.default_backend?.image || 'trellis';
		const target =
			els.engine.querySelector(`button[data-backend="${fallbackId}"]:not(:disabled)`) ||
			els.engine.querySelector('button:not(:disabled)');
		if (target) selectEngine(target);
	} else if (
		!userPickedEngine &&
		!hasPhotos &&
		defaultId &&
		defaultId !== selectedEngine.backend
	) {
		const target = els.engine.querySelector(
			`button[data-backend="${defaultId}"]:not(:disabled)`,
		);
		if (target) selectEngine(target);
	}
}

// Flip the engine picker to a backend by id (used by the lane-failover retry
// affordances, so a switch is always VISIBLE in the composer — never silent).
// Returns false when that engine has no live button on this deployment.
function selectEngineByBackend(backendId) {
	const btn = els.engine?.querySelector(`button[data-backend="${backendId}"]:not(:disabled)`);
	if (!btn) return false;
	userPickedEngine = true;
	selectEngine(btn);
	return true;
}

function selectEngine(btn, silent) {
	if (!btn) return;
	selectedEngine = {
		id: btn.dataset.engine,
		path: btn.dataset.path,
		backend: btn.dataset.backend,
		byok: btn.dataset.byok || null,
		polyControl: btn.dataset.poly === 'true',
	};
	for (const b of els.engine.querySelectorAll('button')) {
		b.setAttribute('aria-pressed', String(b === btn));
	}
	updateByokRow();
	updateAspectVisibility();
	if (!silent) updateEstimate();
	// The engine decides whether High is $THREE-gated (platform) or exempt (BYOK), so
	// re-evaluate the lock whenever the engine changes under High. Reuses the cached
	// access verdict — no extra round-trip, no loading flash.
	if (selectedTier === 'high') reflectHighAccess('high', { silent: true });
}

// Show the key field only for BYOK engines, with provider-specific hint + link.
function updateByokRow() {
	if (!els.byokRow) return;
	const byok = selectedEngine.byok;
	els.byokRow.classList.toggle('is-hidden', !byok);
	if (!byok) return;
	const hint = KEY_HINTS[byok];
	const name = hint?.label || byok;
	els.byokLabel.textContent = `${name} key`;
	els.providerKey.placeholder = `Your ${name} API key (kept in this browser)`;
	els.byokHint.innerHTML = hint
		? `This engine runs on your own ${hint.label} key. <a href="${hint.url}" target="_blank" rel="noopener">Get a key →</a> Signed-in users can save it once in Account instead.`
		: `This engine runs on your own ${name} key, kept in this browser. Signed-in users can save it in Account instead.`;
}

function selectTier(tierId) {
	if (!['draft', 'standard', 'high'].includes(tierId)) return;
	selectedTier = tierId;
	for (const b of els.tier.querySelectorAll('button')) {
		b.setAttribute('aria-pressed', String(b.dataset.tier === tierId));
	}
	// Tier changes can move the default engine (draft prefers the free lane).
	updateEngineAvailability();
	updateEstimate();
	reflectHighAccess(tierId);
}

// The High tier is a $THREE holder perk (gated server-side). When the user picks
// it, surface their access up front — a frosted lock with a Get $THREE path for
// non-holders (and the Generate button disabled for High), an "Unlocked" ribbon
// for holders (pass primed so their request clears the gate without a round-trip
// stall). Draft and Standard clear the lock (they're free, never gated). Degrades
// safely: if the access read fails we show a retry but DON'T trap the user — the
// server stays the final authority and a 403 falls back to the upsell modal.
let _accessHost = null;
let highLocked = false; // true → High is selected but the holder isn't eligible
let _highAccess = null; // last resolved forge.high access payload (for the gate modal)

// The only combination the server actually $THREE-gates: High tier on a PLATFORM-keyed
// backend. BYOK engines run on the caller's own vendor key, so the server exempts BYOK
// High (key-gated, not hold-gated) — and so must the client, or a non-holder with their
// own Meshy/Tripo/Rodin key would be wrongly blocked from High. Draft/Standard are never
// gated. Every client gate check keys on this, so the lock can never engage outside it.
function highTierNeedsPass() {
	return selectedTier === 'high' && !selectedEngine.byok;
}

function accessHost() {
	if (_accessHost || !els.tier) return _accessHost;
	const host = document.createElement('div');
	host.className = 'fq-access';
	host.hidden = true;
	(els.estimate || els.tier).insertAdjacentElement('afterend', host);
	_accessHost = host;
	return host;
}

// Reflect the High-tier gate onto the Generate button: disabled + relabelled
// while High is selected and the user is ineligible. Only touches the button when
// not mid-job (setBusy owns the busy label).
function applyHighGate() {
	if (!els.generate || els.generate.dataset.busy === '1') return;
	const locked = highTierNeedsPass() && highLocked;
	els.generate.disabled = locked;
	els.generate.classList.toggle('is-gated', locked);
	if (els.generateLabel) {
		els.generateLabel.textContent = locked ? 'Hold $THREE for High' : 'Generate';
	}
}

async function reflectHighAccess(tierId, { silent = false } = {}) {
	const host = accessHost();
	if (!host) return;
	if (tierId !== 'high') {
		highLocked = false;
		_highAccess = null;
		renderLock(host, { clear: true });
		// High isn't selected — let the persistent hint advertise it again.
		if (els.holderNote) els.holderNote.hidden = false;
		applyHighGate();
		return;
	}
	// High on a BYOK engine is server-exempt (the caller's own vendor key pays), so it's
	// never $THREE-gated here either: clear any lock, drop the holder note, and let the
	// BYOK key flow take over. This is the path that keeps BYOK High byte-for-byte free.
	if (!highTierNeedsPass()) {
		highLocked = false;
		renderLock(host, { clear: true });
		if (els.holderNote) els.holderNote.hidden = true;
		applyHighGate();
		return;
	}
	// Platform-keyed High — the real $THREE gate. The in-place lock panel takes over, so
	// the small persistent hint stands down to avoid stacking two "holder feature" notes.
	if (els.holderNote) els.holderNote.hidden = true;
	// Re-evaluating after an engine switch (silent) reuses the last resolved verdict so
	// the panel doesn't flash a loading state for a check we already made.
	let access = silent && _highAccess ? _highAccess : null;
	if (!access) {
		renderLock(host, { loading: true });
		const data = await getAccess('forge.high');
		// User moved off High, or switched to a BYOK engine, while we fetched.
		if (!highTierNeedsPass()) return;
		access = data?.access || null;
	}
	if (!access) {
		// Access read failed — show a retry, but don't lock (fail open; the server
		// enforces and a real holder isn't trapped behind a transient hiccup).
		_highAccess = null;
		highLocked = false;
		renderLock(host, { error: true, onRetry: () => reflectHighAccess('high') });
		applyHighGate();
		return;
	}
	_highAccess = access;
	highLocked = !access.eligible;
	renderLock(
		host,
		lockStateFromAccess(access, {
			getThreeUrl: '/three-token',
			onUseFree: () => selectTier('standard'),
			useFreeLabel: 'Use Standard (free)',
			// Working Pay-per-use CTA: pay $THREE for one High generation in place.
			onPayPerUse: (pay) => payThenGenerate(pay),
		}),
	);
	applyHighGate();
	// Keep the persistent button pill + note in sync with the fresh verdict.
	applyHighAffordances(access);
	// Reflect the resolved hold in the cost line too — High flips to "Free" for a
	// holder without a reload.
	updateEstimate();
	if (access.eligible) primeTierPass();
}

// Small lock glyph for the High-tier button pill. Stroke = currentColor so it
// tracks the pill's locked (gold) / unlocked (green) tone.
const TIER_LOCK_SVG =
	'<svg class="tier-lock-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>';

// Paint the persistent High-tier affordances — the lock pill on the High button
// and the inline holder note under the Quality row — from a single-feature access
// payload (the `.access` from getAccess('forge.high'), or a 403 gate body, which
// both carry `eligible`/`required`/`held`). Holders get the quiet unlocked
// treatment; everyone else (and the null/unknown case) keeps the $THREE lock so
// High reads as the premium lane before it's ever selected. Purely cosmetic — the
// server stays the only authority on eligibility.
function applyHighAffordances(access) {
	const eligible = Boolean(access?.eligible);
	const state = eligible ? 'unlocked' : 'locked';
	const btn = els.tier?.querySelector('button[data-tier="high"]');
	if (btn) {
		btn.dataset.access = state;
		btn.setAttribute(
			'aria-label',
			eligible ? 'High quality — unlocked, you hold $THREE' : 'High quality — $THREE holder feature',
		);
		const pill = btn.querySelector('.tier-lock');
		if (pill) {
			pill.dataset.state = state;
			pill.title = eligible ? 'Unlocked — you hold $THREE' : 'High quality is a $THREE holder feature';
			pill.innerHTML = eligible
				? '<span class="tier-lock-ico" aria-hidden="true">✓</span><span class="tier-lock-txt">$THREE</span>'
				: `${TIER_LOCK_SVG}<span class="tier-lock-txt">$THREE</span>`;
		}
	}
	const note = els.holderNote;
	if (note) {
		note.dataset.state = state;
		note.innerHTML = eligible
			? '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is unlocked — you hold <a href="/three-token">$THREE</a>.'
			: '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is a <a href="/three-token">$THREE holder</a> feature — hold to unlock, or pay per generation.';
	}
}

// One-time read on load: reflect the viewer's forge.high access onto the High
// button pill + the inline note so the holder gate is legible before the tier is
// even selected. Seeds the gate cache and primes the tier pass for real holders so
// their first High submit clears the server gate without an RPC stall.
async function reflectHighButtonAccess() {
	const data = await getAccess('forge.high');
	const access = data?.access || null;
	if (access) _highAccess = access;
	applyHighAffordances(access);
	if (access?.eligible) primeTierPass();
}

// $THREE holder free-generation multiplier by tier level — mirrors api/_lib/three-tier.js
// (rateMultiplier), which the free lane applies to a holder's quota via the tier pass.
const FREE_MULT_BY_LEVEL = { 1: 2, 2: 3, 3: 5, 4: 10 };

// The quiet holder line under Generate (Part A): a holder sees their active free-quota
// multiplier; everyone else sees a non-blocking upsell plus a reachable wallet-connect so
// a holder who hasn't connected can reveal their perk. Reads the shared, wallet-aware
// access matrix — never nags, never blocks the free base lane.
async function updatePerkLine() {
	if (!els.perkRow || !els.perkLine) return;
	const data = await getAccess();
	const level = Number(data?.tier?.level) || 0;
	const connected = Boolean(getConnectedWalletAddress());
	els.perkRow.hidden = false;
	if (level >= 1) {
		const mult = FREE_MULT_BY_LEVEL[level] || 1;
		els.perkLine.dataset.state = 'perk';
		els.perkLine.innerHTML =
			'<span class="fq-perk-ico" aria-hidden="true">⚡</span> Holder perk: ' +
			`<strong>${mult}× free quota</strong> · <a href="/three#tiers">your $THREE tier</a>`;
		if (els.connectBtn) els.connectBtn.hidden = true;
	} else {
		els.perkLine.dataset.state = 'upsell';
		els.perkLine.innerHTML =
			'<a href="/three#tiers">Hold $THREE for up to 10× free generations →</a>';
		// Offer connect only when there's no wallet in hand to read a tier from.
		if (els.connectBtn) els.connectBtn.hidden = connected;
	}
}

// The honest price for the current engine + tier, as a styled segment. The web
// gate charges only High tier (hold $THREE or pay per generation); Draft and
// Standard run free on the platform's rate-limited lanes; BYOK engines bill the
// caller's own provider key. `_highAccess.eligible` reflects a resolved $THREE
// hold, so a holder sees High as already unlocked.
function costSegment(backend, tierMeta) {
	if (backend.byok) return 'billed to your own key';
	if (tierMeta.id === 'high') {
		return _highAccess?.eligible
			? '<span class="est-free">Free</span> · you hold $THREE'
			: `<span class="est-cost">$${tierMeta.price_usdc}</span> or hold $THREE`;
	}
	return '<span class="est-free">Free</span>';
}

// Render the honest time/cost/poly estimate for the current engine + tier from
// the catalog. No fabricated numbers — everything comes from /api/forge?catalog.
function updateEstimate() {
	if (!els.estimate || !catalog) return;
	const backend = catalog.backends.find((b) => b.id === selectedEngine.backend);
	const tierMeta = catalog.tiers.find((t) => t.id === selectedTier);
	if (!backend || !tierMeta) {
		els.estimate.textContent = '';
		return;
	}
	const est = (backend.estimates?.[selectedEngine.path] || []).find(
		(e) => e.tier === selectedTier,
	);
	// Holder-readable, not pipeline-internal: say how long it usually takes and
	// what the engine does, in plain words. The mechanism ("builds from a
	// reference image") replaces jargon like "image-intermediate · fast path".
	const parts = [`<strong>${tierMeta.label}</strong>`, costSegment(backend, tierMeta)];
	if (est?.eta_seconds) parts.push(`usually ~${est.eta_seconds}s`);
	if (est && est.credits != null) parts.push(`~${est.credits} credits`);
	if (backend.poly_control) parts.push(`up to ${tierMeta.polycount.toLocaleString()} polygons`);
	if (selectedEngine.path === 'geometry') parts.push('shapes geometry straight from the prompt');
	else if (selectedEngine.path === 'sketch') parts.push('untextured geometry from your sketch');
	else parts.push('builds from a reference image');
	els.estimate.innerHTML = parts.join(' · ');
}

// View slots ------------------------------------------------------------------

function buildSlots() {
	els.viewsGrid.innerHTML = '';
	slots.forEach((_, i) => {
		const slot = document.createElement('div');
		slot.className = 'view-slot';
		slot.dataset.index = String(i);
		slot.tabIndex = 0;
		slot.setAttribute('role', 'button');

		slot.innerHTML = `
			<div class="vs-empty">
				<span class="vs-icon" aria-hidden="true">+</span>
				<span class="vs-label">${VIEW_LABELS[i]}</span>
			</div>
			<div class="vs-uploading">
				<div class="shimmer" aria-hidden="true"></div>
				<span>Uploading…</span>
			</div>
			<img loading="lazy" decoding="async" class="vs-thumb" alt="" />
			<span class="vs-badge">${VIEW_LABELS[i]}</span>
			<button type="button" class="vs-remove" aria-label="Remove ${VIEW_LABELS[i]} view">×</button>
			<div class="vs-error">
				<span class="vs-error-msg">Upload failed</span>
				<button type="button" class="vs-retry">Retry</button>
			</div>`;

		// Remove (stop click from also re-opening the picker).
		slot.querySelector('.vs-remove').addEventListener('click', (e) => {
			e.stopPropagation();
			clearSlot(i);
		});
		// Retry re-opens the picker for this slot.
		slot.querySelector('.vs-retry').addEventListener('click', (e) => {
			e.stopPropagation();
			openPicker(i);
		});

		// Click empty/error → browse for this slot.
		slot.addEventListener('click', () => {
			if (slots[i].state === 'empty' || slots[i].state === 'error') openPicker(i);
		});
		slot.addEventListener('keydown', (e) => {
			if (e.key === 'Enter' || e.key === ' ') {
				e.preventDefault();
				if (slots[i].state === 'empty' || slots[i].state === 'error') openPicker(i);
			}
		});

		// Drag to reorder (uploaded slots only).
		slot.addEventListener('dragstart', (e) => {
			if (slots[i].state !== 'uploaded') {
				e.preventDefault();
				return;
			}
			e.dataTransfer.setData('application/x-forge-slot', String(i));
			e.dataTransfer.effectAllowed = 'move';
			slot.classList.add('dragging');
		});
		slot.addEventListener('dragend', () => slot.classList.remove('dragging'));

		// Drop target — accepts files OR a dragged thumbnail (reorder).
		slot.addEventListener('dragover', (e) => {
			e.preventDefault();
			e.dataTransfer.dropEffect = e.dataTransfer.types.includes('application/x-forge-slot')
				? 'move'
				: 'copy';
			slot.classList.add('drop-target');
		});
		slot.addEventListener('dragleave', () => slot.classList.remove('drop-target'));
		slot.addEventListener('drop', (e) => {
			e.preventDefault();
			slot.classList.remove('drop-target');
			const from = e.dataTransfer.getData('application/x-forge-slot');
			if (from !== '') {
				swapSlots(Number(from), i);
			} else if (e.dataTransfer.files?.length) {
				handleFiles(i, e.dataTransfer.files);
			}
		});

		els.viewsGrid.appendChild(slot);
		renderSlot(i);
	});
}

function slotEl(i) {
	return els.viewsGrid.querySelector(`.view-slot[data-index="${i}"]`);
}

// One pip per possible reference view — filled as photos upload.
function buildViewsPips() {
	if (!els.viewsPips || els.viewsPips.childElementCount) return;
	for (let i = 0; i < MAX_VIEWS; i++) {
		const pip = document.createElement('i');
		pip.dataset.filled = 'false';
		els.viewsPips.appendChild(pip);
	}
}

// Live "N of 4 views" readout + pips. Teaches that more views sharpen the mesh,
// so users don't stop at a single photo thinking it's enough.
function updateViewsCounter() {
	if (!els.viewsCounter || !els.viewsCounterText) return;
	const n = slots.filter((s) => s.state === 'uploaded').length;
	const pips = els.viewsPips ? els.viewsPips.children : [];
	for (let i = 0; i < pips.length; i++) pips[i].dataset.filled = String(i < n);
	let tail;
	if (n === 0) tail = ' — add a photo to begin';
	else if (n < MAX_VIEWS) tail = ' · <span class="vc-quality">more views = sharper</span>';
	else tail = ' · <span class="vc-quality">full coverage</span>';
	els.viewsCounterText.innerHTML = `<strong>${n}</strong> of ${MAX_VIEWS} views${tail}`;
}

function renderSlot(i) {
	const el = slotEl(i);
	if (!el) return;
	const s = slots[i];
	el.dataset.state = s.state;
	el.draggable = s.state === 'uploaded';
	// Slot changes flip the input mode (prompt-only ↔ photo), which changes
	// which engines may serve — keep the selector honest in the same frame.
	updateEngineAvailability();
	updateViewsCounter();

	const img = el.querySelector('.vs-thumb');
	if (s.objectUrl) {
		img.src = s.objectUrl;
		img.alt = `${VIEW_LABELS[i]} view`;
	} else {
		img.removeAttribute('src');
		img.alt = '';
	}
	el.querySelector('.vs-error-msg').textContent = s.errorMsg || 'Upload failed';

	const labels = {
		empty: `${VIEW_LABELS[i]} view, empty — add a photo`,
		uploading: `${VIEW_LABELS[i]} view, uploading`,
		uploaded: `${VIEW_LABELS[i]} view, uploaded — drag to reorder`,
		error: `${VIEW_LABELS[i]} view, upload failed`,
	};
	el.setAttribute('aria-label', labels[s.state] || VIEW_LABELS[i]);
}

function clearSlot(i) {
	const s = slots[i];
	if (s.objectUrl) URL.revokeObjectURL(s.objectUrl);
	slots[i] = { state: 'empty', url: null, objectUrl: null, errorMsg: '' };
	renderSlot(i);
}

function swapSlots(a, b) {
	if (a === b) return;
	const tmp = slots[a];
	slots[a] = slots[b];
	slots[b] = tmp;
	renderSlot(a);
	renderSlot(b);
}

function firstFreeSlot() {
	return slots.findIndex((s) => s.state === 'empty' || s.state === 'error');
}

function nextFreeAfter(i) {
	for (let j = i + 1; j < MAX_VIEWS; j++) {
		if (slots[j].state === 'empty' || slots[j].state === 'error') return j;
	}
	return -1;
}

function openPicker(index) {
	pickerTarget = index;
	els.fileInput.value = '';
	els.fileInput.click();
}

// Distribute dropped/picked files into slots, starting at `startIndex` (or the
// first free slot when null), filling free slots up to MAX_VIEWS.
function handleFiles(startIndex, fileList) {
	const files = Array.from(fileList).filter((f) => f && f.type && f.type.startsWith('image/'));
	if (!files.length) return;
	let idx = startIndex == null ? firstFreeSlot() : startIndex;
	for (const file of files) {
		if (idx < 0 || idx >= MAX_VIEWS) idx = firstFreeSlot();
		if (idx < 0) break; // all slots taken
		uploadToSlot(idx, file);
		idx = nextFreeAfter(idx);
	}
}

// Presign → PUT to object storage → public URL. Shared by the view slots and
// the sketch uploader. Returns { ok: true, url } or { ok: false, message }.
async function presignAndPut(file) {
	// Two legs, two catches on purpose. The presign leg is same-origin, so a
	// throw there really is the user's connection. The PUT leg is cross-origin to
	// the bucket, where a rejected credential or a missing CORS rule answers 403
	// with no Access-Control-Allow-Origin, and the browser hands us a rejected
	// promise with no status to read. Reporting that as a network fault (one
	// shared catch, as this had until 2026-09-08) blames the user's phone for our
	// outage and sends them into an endless Retry loop.
	let presign;
	let presignRes;
	try {
		presignRes = await fetch('/api/forge-upload', {
			method: 'POST',
			headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
			body: JSON.stringify({ content_type: file.type, size_bytes: file.size }),
		});
		presign = await presignRes.json().catch(() => ({}));
	} catch {
		return { ok: false, message: 'No connection. Check your network.' };
	}

	if (presignRes.status === 503) {
		// The server distinguishes "this deployment has no storage" from "our
		// storage is refusing us right now"; only the second is worth asking the
		// user to come back for.
		return {
			ok: false,
			message:
				presign.error === 'storage_unavailable'
					? 'Uploads are down right now. Try again shortly.'
					: 'Uploads unavailable on this deployment.',
		};
	}
	if (presignRes.status === 429) return { ok: false, message: 'Rate limited. Retry shortly.' };
	if (!presignRes.ok || !presign.upload_url || !presign.public_url) {
		return { ok: false, message: presign.message || 'Upload failed.' };
	}

	try {
		const putRes = await fetch(presign.upload_url, {
			method: 'PUT',
			headers: { 'content-type': file.type },
			body: file,
		});
		if (!putRes.ok) return { ok: false, message: `Storage rejected the file (${putRes.status}).` };
		return { ok: true, url: presign.public_url };
	} catch {
		return { ok: false, message: 'Storage refused the upload. Try again shortly.' };
	}
}

// Upload one file into a slot: presign → PUT to object storage → record the
// public URL. The slot moves empty/error → uploading → uploaded|error, each a
// real, designed state. The local blob preview shows immediately.
async function uploadToSlot(index, file) {
	if (!ACCEPTED_TYPES.has(file.type)) {
		setSlotError(index, 'Use PNG, JPG, or WebP.');
		return;
	}
	if (file.size === 0) {
		setSlotError(index, 'File is empty.');
		return;
	}
	if (file.size > MAX_UPLOAD_BYTES) {
		setSlotError(index, 'Too large (max 8 MB).');
		return;
	}

	const prev = slots[index];
	if (prev.objectUrl) URL.revokeObjectURL(prev.objectUrl);
	const objectUrl = URL.createObjectURL(file);
	slots[index] = { state: 'uploading', url: null, objectUrl, errorMsg: '' };
	renderSlot(index);

	const up = await presignAndPut(file);
	if (!up.ok) {
		setSlotError(index, up.message);
		return;
	}
	// Success — keep the local blob preview, remember the public URL.
	slots[index] = { state: 'uploaded', url: up.url, objectUrl, errorMsg: '' };
	renderSlot(index);
}

function setSlotError(index, message) {
	const s = slots[index];
	// Keep any local preview so the user sees what failed.
	slots[index] = {
		state: 'error',
		url: null,
		objectUrl: s.objectUrl || null,
		errorMsg: message,
	};
	renderSlot(index);
}

function uploadedUrls() {
	return slots.filter((s) => s.state === 'uploaded' && s.url).map((s) => s.url);
}

// Sketch slot ------------------------------------------------------------------
// One drawing, built from the same .view-slot kit as the photo slots so every
// state (empty / uploading / uploaded / error) is already designed.

function sketchSlotEl() {
	return els.sketchGrid?.querySelector('.view-slot') || null;
}

function buildSketchSlot() {
	if (!els.sketchGrid || els.sketchGrid.childElementCount) return;
	const slot = document.createElement('div');
	slot.className = 'view-slot';
	slot.tabIndex = 0;
	slot.setAttribute('role', 'button');
	slot.innerHTML = `
		<div class="vs-empty">
			<span class="vs-icon" aria-hidden="true">✎</span>
			<span class="vs-label">Sketch</span>
		</div>
		<div class="vs-uploading">
			<div class="shimmer" aria-hidden="true"></div>
			<span>Uploading…</span>
		</div>
		<img loading="lazy" decoding="async" class="vs-thumb" alt="" />
		<span class="vs-badge">Sketch</span>
		<button type="button" class="vs-remove" aria-label="Remove sketch">×</button>
		<div class="vs-error">
			<span class="vs-error-msg">Upload failed</span>
			<button type="button" class="vs-retry">Retry</button>
		</div>`;

	slot.querySelector('.vs-remove').addEventListener('click', (e) => {
		e.stopPropagation();
		clearSketch();
	});
	slot.querySelector('.vs-retry').addEventListener('click', (e) => {
		e.stopPropagation();
		openSketchPicker();
	});
	slot.addEventListener('click', () => {
		if (sketch.state === 'empty' || sketch.state === 'error') openSketchPicker();
	});
	slot.addEventListener('keydown', (e) => {
		if (e.key === 'Enter' || e.key === ' ') {
			e.preventDefault();
			if (sketch.state === 'empty' || sketch.state === 'error') openSketchPicker();
		}
	});
	slot.addEventListener('dragover', (e) => {
		e.preventDefault();
		e.dataTransfer.dropEffect = 'copy';
		slot.classList.add('drop-target');
	});
	slot.addEventListener('dragleave', () => slot.classList.remove('drop-target'));
	slot.addEventListener('drop', (e) => {
		e.preventDefault();
		slot.classList.remove('drop-target');
		const file = e.dataTransfer.files?.[0];
		if (file) uploadSketch(file);
	});

	els.sketchGrid.appendChild(slot);
	renderSketchSlot();
}

function openSketchPicker() {
	if (!els.sketchFileInput) return;
	els.sketchFileInput.value = '';
	els.sketchFileInput.click();
}

function renderSketchSlot() {
	const el = sketchSlotEl();
	if (!el) return;
	el.dataset.state = sketch.state;
	const img = el.querySelector('.vs-thumb');
	if (sketch.objectUrl) {
		img.src = sketch.objectUrl;
		img.alt = 'Your sketch';
	} else {
		img.removeAttribute('src');
		img.alt = '';
	}
	el.querySelector('.vs-error-msg').textContent = sketch.errorMsg || 'Upload failed';
	const labels = {
		empty: 'Sketch, empty — add a drawing',
		uploading: 'Sketch, uploading',
		uploaded: 'Sketch, uploaded',
		error: 'Sketch, upload failed',
	};
	el.setAttribute('aria-label', labels[sketch.state] || 'Sketch');
}

function clearSketch() {
	if (sketch.objectUrl) URL.revokeObjectURL(sketch.objectUrl);
	Object.assign(sketch, { state: 'empty', url: null, objectUrl: null, errorMsg: '' });
	renderSketchSlot();
}

async function uploadSketch(file) {
	if (!ACCEPTED_TYPES.has(file.type)) {
		Object.assign(sketch, { state: 'error', url: null, errorMsg: 'Use PNG, JPG, or WebP.' });
		renderSketchSlot();
		return;
	}
	if (file.size === 0) {
		Object.assign(sketch, { state: 'error', url: null, errorMsg: 'File is empty.' });
		renderSketchSlot();
		return;
	}
	if (file.size > MAX_UPLOAD_BYTES) {
		Object.assign(sketch, { state: 'error', url: null, errorMsg: 'Too large (max 8 MB).' });
		renderSketchSlot();
		return;
	}
	if (sketch.objectUrl) URL.revokeObjectURL(sketch.objectUrl);
	Object.assign(sketch, {
		state: 'uploading',
		url: null,
		objectUrl: URL.createObjectURL(file),
		errorMsg: '',
	});
	renderSketchSlot();

	const up = await presignAndPut(file);
	if (up.ok) Object.assign(sketch, { state: 'uploaded', url: up.url, errorMsg: '' });
	else Object.assign(sketch, { state: 'error', url: null, errorMsg: up.message });
	renderSketchSlot();
}

function firstPreviewUrl() {
	const s = slots.find((x) => x.state === 'uploaded' && (x.objectUrl || x.url));
	return s ? s.objectUrl || s.url : null;
}

// Job submission --------------------------------------------------------------

// Headers for a forge request, including the BYOK provider key (geometry path)
// when the user has entered one. The key rides a header, never the URL.
function forgeHeaders(extra) {
	const h = { ...CLIENT_HEADERS, ...extra };
	if (providerKey) h['x-forge-provider-key'] = providerKey;
	// Carry the holder's $THREE tier pass so an eligible holder clears the High-tier
	// gate (and gets their free-lane multiplier). No-op for anonymous users — the
	// request simply proceeds at the base entitlement.
	attachTierPass(h);
	return h;
}

async function startJob({ prompt, imageUrls, skipValidation, payment }) {
	const base = { path: selectedEngine.path, tier: selectedTier, backend: selectedEngine.backend };
	const body =
		Array.isArray(imageUrls) && imageUrls.length
			? { image_urls: imageUrls, prompt: prompt || undefined, ...base }
			: { prompt, aspect_ratio: aspectRatio, ...base };
	// What this maker said they are building for, remembered from an earlier
	// model. Absent until they answer once; the server ignores an unknown value.
	const destination = storedForgeDestination();
	if (destination) body.destination = destination;
	// Caller already saw the vision warning and chose to proceed (Consumer 1).
	if (skipValidation) body.skip_validation = true;
	// Pay-per-use proof: a non-holder who paid $THREE for this High generation
	// presents the settled payment so the server's gate is satisfied per use.
	if (payment?.paymentId && payment?.refId) {
		body.payment_id = payment.paymentId;
		body.ref_id = payment.refId;
	}

	// Platform-keyed High is the $THREE-gated combination — mint/refresh the holder's tier
	// pass and AWAIT it so forgeHeaders attaches a fresh, RPC-free proof on this very
	// request. An eligible holder then clears the server gate even if a live on-chain read
	// would hiccup, and even when they submit faster than the background primeTierPass()
	// could finish. An eligible *connected* wallet (no signed-in account) signs once here to
	// prove ownership — interactive only when eligible so a non-holder is never popped a
	// signature; a signed-in holder still mints silently via their session. No-op for
	// anonymous callers, the free tiers, and BYOK High (server-exempt — no pass needed).
	if (highTierNeedsPass()) await getTierPass({ interactive: Boolean(_highAccess?.eligible) });

	const res = await fetch('/api/forge', {
		method: 'POST',
		headers: forgeHeaders({ 'content-type': 'application/json' }),
		body: JSON.stringify(body),
	});
	const data = await res.json().catch(() => ({}));
	// An explicitly picked free engine that could not serve the request (503
	// provider_busy). Checked before the generic 503 handling below, which would
	// misfile it. When the server names configured engines that can take the
	// request, hop to one visibly (the lane_failed path flips the picker and says
	// so) rather than count down into the same dead lane; otherwise it is the
	// recoverable high-demand countdown.
	if (data.error === 'provider_busy') {
		const e = new Error(data.message || 'The free 3D engines are at capacity right now.');
		if (Array.isArray(data.retry_backends) && data.retry_backends.length) {
			e.kind = 'lane_failed';
			e.retryBackends = data.retry_backends;
		} else {
			e.kind = 'busy';
			e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15;
		}
		throw e;
	}
	if (res.status === 503 || data.error === 'unconfigured') {
		const e = new Error(data.message || 'unconfigured');
		e.kind = 'unconfigured';
		throw e;
	}
	// Geometry path needs a BYOK key we don't have — a recoverable, designed state.
	if (data.error === 'needs_key') {
		const e = new Error(data.message || 'An API key is required for this engine.');
		e.kind = 'needs_key';
		e.provider = data.provider;
		throw e;
	}
	if (data.error === 'invalid_key') {
		const e = new Error(data.message || 'The provider rejected this API key.');
		e.kind = 'invalid_key';
		throw e;
	}
	if (data.error === 'insufficient_credits') {
		const e = new Error(data.message || 'The provider account is out of credits.');
		e.kind = 'credits';
		throw e;
	}
	// Vision pre-check rejected the reference photo (Consumer 1). Recoverable:
	// the user can swap the photo (Try again) or override (Generate anyway).
	if (res.status === 422 && data.error === 'image_not_usable') {
		const e = new Error(data.message || 'That photo doesn’t look usable for 3D.');
		e.kind = 'not_usable';
		throw e;
	}
	if (res.status === 429 || data.error === 'rate_limited') {
		const headerReset = Number(res.headers.get('ratelimit-reset'));
		const secs =
			Number(data.retry_after) > 0
				? Math.ceil(Number(data.retry_after))
				: headerReset > 0
					? Math.ceil(headerReset)
					: 10;
		// `rate_limiter_unavailable` means the distributed limiter (Redis) is down
		// and the paid lane is failing closed — not that the user spent their quota.
		const unavailable = data.reason === 'rate_limiter_unavailable';
		const e = new Error(
			data.message ||
				(unavailable
					? 'The generator is temporarily unavailable. Refine your current model locally, or try again shortly.'
					: `You've hit the generation limit. It resets in about ${secs}s.`),
		);
		e.kind = 'rate_limited';
		e.retryAfter = secs;
		e.unavailable = unavailable;
		throw e;
	}
	// High-tier hold-to-access gate ($THREE) — a hold-OR-pay 402 (three_hold_required).
	// Recoverable: the user can hold $THREE (Get $THREE) or drop to Draft/Standard.
	// Carries the full gate payload (held vs required, usd_to_go, acquire, pay_per_use)
	// straight to the upsell modal.
	if (res.status === 402 && data.error === 'three_hold_required') {
		const e = new Error(data.message || 'High-quality generation is a $THREE holder perk.');
		e.kind = 'hold_required';
		e.gate = data;
		throw e;
	}
	// Pay-per-use proof was rejected (bad/expired payment) or already spent — both
	// recoverable by paying again. payment_invalid/expired re-offer Pay; an already
	// used payment also clears the stale proof so a retry doesn't replay it.
	if (
		res.status === 402 &&
		(data.error === 'payment_invalid' || data.error === 'payment_expired')
	) {
		const e = new Error(data.message || 'That $THREE payment could not be verified.');
		e.kind = 'payment_invalid';
		e.gate = data;
		throw e;
	}
	if (res.status === 409 && data.error === 'payment_already_used') {
		const e = new Error(data.message || 'That payment was already used. Pay again to generate.');
		e.kind = 'payment_used';
		e.gate = data;
		throw e;
	}
	// Free lane shed this request at the fleet concurrency cap — an influx of
	// demand, not the user's quota. Recoverable with a short auto-retry, framed as
	// "high demand" rather than a failure the user caused. (provider_busy comes
	// from an explicit free-engine pick at capacity; free_lane_unavailable from the
	// Spaces chain being briefly all-down.)
	if (data.error === 'provider_busy' || data.error === 'free_lane_unavailable') {
		const e = new Error(data.message || 'The free 3D engines are at capacity right now.');
		e.kind = 'busy';
		e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15;
		throw e;
	}
	if (!res.ok) {
		throw new Error(data.message || `The generator returned ${res.status}.`);
	}
	return data;
}

async function pollUntilDone(jobId) {
	let deadline = performance.now() + MAX_POLL_MS;
	// Queue-state tracking: a job waiting for a GPU is alive, so say so (after a
	// short grace that filters dispatch latency) and never spend the run budget
	// on line time.
	let queuedPolls = 0;
	let inQueue = false;
	let preQueueMeshLabel = null;
	while (!pollAbort && performance.now() < deadline) {
		await sleep(POLL_INTERVAL_MS);
		if (pollAbort) return null;
		const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, {
			headers: forgeHeaders(),
		});
		const data = await res.json().catch(() => ({}));
		if (data.error === 'unconfigured') {
			const e = new Error(data.message || 'unconfigured');
			e.kind = 'unconfigured';
			throw e;
		}
		if (data.status === 'done' && data.glb_url) return data;
		if (data.status === 'failed') {
			// The server names the configured lanes that can still serve a fresh
			// retry of this request (retry_backends) — carry them so the catch can
			// auto-hop to a backup engine instead of dead-ending.
			const e = new Error(data.error || 'Generation failed.');
			if (data.retryable && Array.isArray(data.retry_backends) && data.retry_backends.length) {
				e.kind = 'lane_failed';
				e.retryBackends = data.retry_backends;
			}
			throw e;
		}
		if (data.status === 'queued') {
			setStep('mesh', 'active');
			deadline = performance.now() + MAX_POLL_MS;
			queuedPolls += 1;
			// A cold start is stated by the API, not guessed from how long we have
			// been waiting, so it skips the 3-poll grace and names itself on the
			// first frame that reports it. The label is rewritten every poll, so the
			// boot countdown actually moves instead of freezing on its first value.
			const coldLabel = coldStartLabel(data);
			if (coldLabel) {
				if (!inQueue) {
					inQueue = true;
					preQueueMeshLabel = els.steps?.mesh?.querySelector('span:last-child')?.textContent || null;
				}
				setStepLabel('mesh', coldLabel);
			} else if (!inQueue && queuedPolls >= 3) {
				inQueue = true;
				preQueueMeshLabel = els.steps?.mesh?.querySelector('span:last-child')?.textContent || null;
				setStepLabel('mesh', 'In line for a GPU');
			}
		}
		if (data.status === 'running') {
			setStep('mesh', 'active');
			queuedPolls = 0;
			if (inQueue) {
				inQueue = false;
				if (preQueueMeshLabel) setStepLabel('mesh', preQueueMeshLabel);
			}
		}
	}
	if (pollAbort) return null;
	throw new Error(
		'Generation timed out. The model may be too complex — try fewer views or a simpler prompt.',
	);
}

// Post the human verdict on a creation — the labeled half of the data flywheel.
function sendFeedback(payload) {
	if (!currentCreationId) return;
	fetch('/api/forge-feedback', {
		method: 'POST',
		headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
		body: JSON.stringify({ creation_id: currentCreationId, ...payload }),
		keepalive: true,
	}).catch(() => {});
}

function resetVerdict() {
	if (!els.verdict) return;
	for (const b of els.verdict.querySelectorAll('button')) {
		b.setAttribute('aria-pressed', 'false');
	}
}

// "Making this for" chips (src/shared/forge-destination-picker.js). The answer is
// written onto the model on screen and remembered for later generations.
const destinationPicker = initForgeDestinationPicker({
	picker: els.destinationPicker,
	status: els.destinationStatus,
	onChoose: (id) => sendFeedback({ destination: id }),
});

function resetCategoryPicker() {
	if (!els.categoryPicker) return;
	els.categoryPicker.querySelectorAll('.forge-cat-btn').forEach((b) => b.classList.remove('active'));
}

function sendCategory(modelCategory) {
	if (!currentCreationId) return;
	fetch('/api/forge-categorize', {
		method: 'POST',
		headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
		body: JSON.stringify({ creation_id: currentCreationId, model_category: modelCategory }),
		keepalive: true,
	}).catch(() => {});
}

// Poster capture — the visual half of every creation card. Image-intermediate
// engines store their flux reference image as the preview, but geometry-first
// and sketch lanes paint no image at all, so their gallery/showcase cards used
// to render as glyph placeholders. Once the finished mesh is standing in the
// viewer, render it onto a small studio-backdrop canvas and attach it to the
// creation row (POST /api/forge-poster — fill-only, owner-scoped, best-effort).
const POSTER_MAX_DIM = 640;
const postedPosters = new Set();

function renderPosterFrame(sourceDataUrl) {
	return new Promise((resolve) => {
		const img = new Image();
		img.onload = () => {
			const scale = Math.min(1, POSTER_MAX_DIM / Math.max(img.width, img.height, 1));
			const w = Math.max(1, Math.round(img.width * scale));
			const h = Math.max(1, Math.round(img.height * scale));
			const canvas = document.createElement('canvas');
			canvas.width = w;
			canvas.height = h;
			const ctx = canvas.getContext('2d');
			if (!ctx) return resolve(null);
			// Same studio backdrop as the live viewer, so mesh posters read as a
			// consistent set next to flux reference images in the galleries.
			const backdrop = ctx.createRadialGradient(w / 2, 0, 0, w / 2, 0, Math.max(w, h) * 1.2);
			backdrop.addColorStop(0, '#1a1612');
			backdrop.addColorStop(0.7, '#0b0a09');
			backdrop.addColorStop(1, '#0b0a09');
			ctx.fillStyle = backdrop;
			ctx.fillRect(0, 0, w, h);
			ctx.drawImage(img, 0, 0, w, h);
			const webp = canvas.toDataURL('image/webp', 0.85);
			// Browsers without webp encoding silently hand back PNG — send what we got.
			resolve(webp.startsWith('data:image/webp') ? webp : canvas.toDataURL('image/png'));
		};
		img.onerror = () => resolve(null);
		img.src = sourceDataUrl;
	});
}

async function capturePoster(creationId) {
	if (!creationId || postedPosters.has(creationId) || !els.viewer?.toDataURL) return;
	postedPosters.add(creationId);
	try {
		if (!els.viewer.loaded) {
			await new Promise((resolve) =>
				els.viewer.addEventListener('load', resolve, { once: true }),
			);
		}
		// Let the materialize entrance settle so the capture is a steady frame.
		await sleep(REDUCED_MOTION ? 300 : 1500);
		// A newer generation or an opened creation replaced the model — skip.
		if (currentCreationId !== creationId) return;
		const frame = await renderPosterFrame(els.viewer.toDataURL('image/png'));
		if (!frame) return;
		const res = await fetch('/api/forge-poster', {
			method: 'POST',
			headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
			body: JSON.stringify({ creation_id: creationId, image: frame }),
		});
		const data = await res.json().catch(() => ({}));
		// The card for this creation is already on screen with a placeholder —
		// refresh the strip so the new poster shows without a reload.
		if (data?.stored) loadGallery();
	} catch {
		// Best-effort: a missed poster never disturbs the result flow.
	}
}

// Render the provenance badge from job metadata: how the mesh was produced
// (engine + tier + path) plus any multi-view conditioning. Shows whatever is
// known — the geometry-first path has no reference views, the image path does.
function setViewsBadge(meta) {
	if (!els.resultViews) return;
	const parts = [];
	const used = Number(meta?.views_used);
	if (Number.isFinite(used) && used >= 1) {
		parts.push(`${used} ${used === 1 ? 'view' : 'views'}`);
		if (meta.multiview) parts.push('multi-view');
	}
	if (meta?.backend) parts.push(ENGINE_LABELS[meta.backend] || meta.backend);
	if (meta?.tier) parts.push(meta.tier);
	if (meta?.path === 'geometry') parts.push('geometry-first');
	if (meta?.path === 'sketch') parts.push('sketch→3D');
	if (parts.length === 0) {
		els.resultViews.classList.add('is-hidden');
		els.resultViews.textContent = '';
		return;
	}
	els.resultViews.textContent = parts.join(' · ');
	els.resultViews.classList.remove('is-hidden');
}

// Materialize entrance — conceal the standing viewer, play the WebGL dissolve
// reveal over it (src/forge-reveal.js), then crossfade back and hand the
// final camera angle to model-viewer so the turntable continues seamlessly.
// Presentation only: any failure restores the viewer immediately.
let revealSeq = 0;
async function playMaterialize(glbUrl) {
	if (REDUCED_MOTION || !els.viewerShell) return;
	const seq = ++revealSeq;
	els.viewer.style.opacity = '0';
	try {
		const { playForgeReveal } = await import('./forge-reveal.js');
		const viewerLoaded = new Promise((resolve) => {
			if (els.viewer.loaded) return resolve();
			els.viewer.addEventListener('load', resolve, { once: true });
		});
		const end = await playForgeReveal({
			container: els.viewerShell,
			glbUrl,
			waitFor: viewerLoaded,
		});
		if (seq === revealSeq && end && Number.isFinite(end.azimuthDeg)) {
			els.viewer.cameraOrbit = `${end.azimuthDeg.toFixed(1)}deg ${end.polarDeg.toFixed(1)}deg auto`;
		}
	} catch {
		// The standing viewer is the fallback — nothing to surface.
	} finally {
		if (seq === revealSeq) els.viewer.style.opacity = '1';
	}
}

// Show "Refine → <next tier>" only when a higher tier exists and the current
// result came from a job we can re-run (a prompt and/or reference images).
function updateRefineButton() {
	if (!els.refine) return;
	const next = nextTierAfter(currentResultTier);
	const reRunnable =
		lastJob &&
		(lastJob.prompt || (Array.isArray(lastJob.imageUrls) && lastJob.imageUrls.length));
	const show = Boolean(next && reRunnable);
	els.refine.classList.toggle('is-hidden', !show);
	if (show) {
		els.refineLabel.textContent = `Refine → ${TIER_LABELS[next]}`;
		els.refine.title = `Re-run this exact ${
			lastJob.imageUrls?.length ? 'reconstruction' : 'prompt'
		} at ${TIER_LABELS[next]} quality`;
	}
}

function showResult(glbUrl, label, meta, { autoSaved = false } = {}) {
	stopElapsed();
	resetVerdict();
	resetCategoryPicker();
	if (els.categoryPicker) els.categoryPicker.hidden = false;
	destinationPicker.show();
	els.viewerShell?.classList.remove('has-load-error');
	// Show the load skeleton over the dark viewport until the GLB paints. The
	// persistent 'load'/'error' listeners below clear it.
	els.viewerShell?.classList.add('is-loading');
	// The viewer fetches the GLB cross-origin, so it needs the dev proxy path on
	// localhost / Codespaces. The free lane returns the finished glb_url in the
	// POST response, which the dev server's r2-url-rewrite middleware skips (it
	// only rewrites GET/HEAD bodies), so the raw r2.dev URL arrives here and the
	// preview dead-ends on CORS. No-op in production. Everything downstream
	// (download, share, segment, refine) keeps the canonical public URL.
	els.viewer.setAttribute('src', resolveDevR2Url(glbUrl));
	els.viewer.setAttribute('alt', `3D model: ${label}`);
	lastShownGlb = glbUrl;
	els.resultLabel.textContent = label;
	// Hide the saved chip by default; caller re-shows it for fresh generations.
	if (els.savedChip) els.savedChip.classList.add('is-hidden');
	setViewsBadge(meta);
	if (autoSaved && els.savedChip) {
		// Re-trigger the animation by forcing a reflow.
		els.savedChip.classList.remove('is-hidden');
		void els.savedChip.offsetWidth;
		els.savedChip.style.animation = 'none';
		void els.savedChip.offsetWidth;
		els.savedChip.style.animation = '';
		// Hide after animation completes (3s).
		setTimeout(() => els.savedChip?.classList.add('is-hidden'), 3100);
	}
	els.download.href = glbUrl;
	els.download.setAttribute(
		'download',
		`${
			label
				.replace(/[^a-z0-9]+/gi, '-')
				.slice(0, 48)
				.replace(/^-|-$/g, '') || 'forge'
		}.glb`,
	);
	// Cross-link into Parts Studio with this exact model pre-loaded.
	if (els.segmentBtn) els.segmentBtn.href = `/segment?mesh=${encodeURIComponent(glbUrl)}`;
	if (els.openInComposer) els.openInComposer.href = `/compose?glb=${encodeURIComponent(glbUrl)}`;
	// Offer "Refine" when a higher tier exists and this job can be re-run. Use the
	// tier the result was actually produced at (meta), falling back to the current
	// selection for re-opened gallery models that don't carry tier metadata.
	currentResultTier = meta?.tier || selectedTier;
	updateRefineButton();
	showState('result');
	playMaterialize(glbUrl);
	// Hand the live model to the Stylize panel (src/forge-stylize.js) so its
	// one-click geometric filters operate on the current source mesh. prompt +
	// creationId are additive fields (existing listeners only read glbUrl/label)
	// consumed by the Iterate panel (conversational refinement) and the Remix
	// panel (publish-as-remixable), both of which need the real prompt to carry
	// forward and the owned creation id to act on.
	document.dispatchEvent(
		new CustomEvent('forge:model-ready', {
			detail: { glbUrl, label, prompt: lastJob?.prompt || '', creationId: currentCreationId },
		}),
	);
	document.dispatchEvent(
		new CustomEvent('tws:feature-done', {
			detail: { feature: 'forge', model: { glbUrl, label } },
		}),
	);
	if (els.forgeShareBtn) {
		els.forgeShareBtn.dataset.sharePrompt = label;
	}
}

// Deterministic gradient from prompt text — same prompt → same colours.
function promptGradient(str) {
	let h = 0;
	for (let i = 0; i < (str || '').length; i++) h = (Math.imul(31, h) + str.charCodeAt(i)) | 0;
	const hue = Math.abs(h) % 360;
	return `linear-gradient(135deg,hsl(${hue},28%,14%) 0%,hsl(${(hue + 40) % 360},22%,10%) 100%)`;
}

function makeGradientThumb(prompt) {
	const ph = document.createElement('span');
	ph.className = 'thumb gradient-ph';
	ph.style.background = promptGradient(prompt);
	if (prompt) {
		const label = document.createElement('span');
		label.className = 'gradient-ph-text';
		label.textContent = prompt;
		ph.appendChild(label);
	}
	return ph;
}

// Load (or reload) the "Your creations" strip from durable storage.
async function loadGallery() {
	if (!els.creations) return;

	els.creations.classList.remove('is-hidden');
	els.creationsGrid.setAttribute('aria-busy', 'true');
	els.creationsGrid.innerHTML = skeletonHTML(4, 'card');

	let data;
	try {
		const res = await fetch('/api/forge-gallery?limit=24', { headers: CLIENT_HEADERS });
		data = await res.json().catch(() => ({}));
	} catch {
		els.creationsGrid.removeAttribute('aria-busy');
		els.creationsGrid.innerHTML = errorStateHTML({
			title: "Couldn't load your creations",
			body: 'Check your connection — your models are still saved.',
		});
		els.creationsGrid.querySelector('[data-sk-retry]')?.addEventListener('click', loadGallery);
		return;
	}

	els.creationsGrid.removeAttribute('aria-busy');
	const creations = Array.isArray(data?.creations) ? data.creations : [];
	if (!data?.enabled || creations.length === 0) {
		els.creations.classList.add('is-hidden');
		return;
	}
	els.creationsGrid.innerHTML = '';
	galleryCreations = creations;
	for (const c of creations) {
		const card = document.createElement('button');
		card.type = 'button';
		card.className = 'creation';
		card.title = c.prompt || 'Forged model';
		card.setAttribute('aria-label', `Open: ${c.prompt || 'forged model'}`);
		if (c.id) card.dataset.creationId = c.id;

		if (c.preview_image_url) {
			const img = document.createElement('img');
			img.className = 'thumb';
			img.loading = 'lazy';
			img.alt = '';
			img.src = c.preview_image_url;
			img.onerror = () => {
				// Thumbnail URL broken — show gradient fallback.
				img.replaceWith(makeGradientThumb(c.prompt));
			};
			card.appendChild(img);
		} else {
			card.appendChild(makeGradientThumb(c.prompt));
		}

		if (c.outcome === 'accepted' || c.outcome === 'rejected') {
			const badge = document.createElement('span');
			badge.className = 'badge';
			badge.dataset.outcome = c.outcome;
			badge.textContent = c.outcome === 'accepted' ? '👍' : '👎';
			card.appendChild(badge);
		}

		// Surface multi-view provenance so the gallery reflects how each model
		// was conditioned.
		if (Number(c.views_used) > 1) {
			const mv = document.createElement('span');
			mv.className = 'badge';
			mv.style.left = '6px';
			mv.style.right = 'auto';
			mv.textContent = `${c.views_used}×`;
			mv.title = `${c.views_used} reference views`;
			card.appendChild(mv);
		}

		// Engine · tier provenance, so the gallery reflects how each was made.
		if (c.backend || c.tier) {
			const prov = document.createElement('span');
			prov.className = 'badge';
			prov.style.left = '6px';
			prov.style.right = 'auto';
			prov.style.top = Number(c.views_used) > 1 ? '28px' : '6px';
			prov.textContent = [ENGINE_LABELS[c.backend] || c.backend, c.tier]
				.filter(Boolean)
				.join(' ');
			prov.title =
				`${c.path === 'geometry' ? 'Geometry-first' : c.path === 'sketch' ? 'Sketch→3D' : 'Image path'} · ${c.backend || ''} · ${c.tier || ''}`.trim();
			card.appendChild(prov);
		}

		const meta = document.createElement('span');
		meta.className = 'meta';
		meta.textContent = c.prompt || 'Untitled';
		card.appendChild(meta);

		card.addEventListener('click', () => openCreation(c));

		// The card is itself a <button>, so the delete control lives beside it in
		// a positioning wrapper rather than nested inside (invalid HTML).
		const cell = document.createElement('div');
		cell.className = 'creation-wrap';
		cell.appendChild(card);
		if (c.id) cell.appendChild(makeDeleteButton(c, cell));
		els.creationsGrid.appendChild(cell);
	}
	els.creationsCount.textContent = `${creations.length} saved`;
	els.creations.classList.remove('is-hidden');
}

// Two-tap delete for a gallery card: the first tap arms a visible "Delete?"
// confirm state, the second (within 4s) permanently deletes the creation
// server-side (the stored model, its preview, and any uploaded reference
// photos) and drops the card in place. Blur, Escape, or the timeout disarms.
function makeDeleteButton(c, cell) {
	const del = document.createElement('button');
	del.type = 'button';
	del.className = 'creation-del';
	del.textContent = '×';
	del.title = 'Delete this creation';
	del.setAttribute('aria-label', `Delete: ${c.prompt || 'forged model'}`);
	let armed = false;
	let disarmTimer = 0;
	const disarm = () => {
		armed = false;
		clearTimeout(disarmTimer);
		del.classList.remove('is-armed');
		del.textContent = '×';
		del.title = 'Delete this creation';
		del.setAttribute('aria-label', `Delete: ${c.prompt || 'forged model'}`);
	};
	del.addEventListener('blur', disarm);
	del.addEventListener('keydown', (e) => {
		if (e.key === 'Escape') disarm();
	});
	del.addEventListener('click', async (e) => {
		// Never let a delete tap open the model underneath.
		e.stopPropagation();
		if (!armed) {
			armed = true;
			del.classList.add('is-armed');
			del.textContent = 'Delete?';
			del.title = 'Click again to permanently delete';
			del.setAttribute('aria-label', 'Confirm permanent delete');
			disarmTimer = setTimeout(disarm, 4000);
			return;
		}
		clearTimeout(disarmTimer);
		del.disabled = true;
		del.textContent = '…';
		let ok = false;
		try {
			const res = await fetch(`/api/forge-creation?id=${encodeURIComponent(c.id)}`, {
				method: 'DELETE',
				headers: CLIENT_HEADERS,
			});
			const body = await res.json().catch(() => ({}));
			// A 404 means the row is already gone (deleted from another tab); the
			// card should disappear either way.
			ok = (res.ok && body?.deleted === true) || res.status === 404;
		} catch {
			ok = false;
		}
		if (!ok) {
			del.disabled = false;
			disarm();
			del.title = "Couldn't delete. Check your connection and try again.";
			return;
		}
		removeCreationFromGallery(c.id, cell);
	});
	return del;
}

// Drop a deleted creation's card in place: no refetch, no skeleton flash.
// Keeps the count and empty state truthful, and clears the feedback handle so
// a verdict can't target the deleted row.
function removeCreationFromGallery(id, cell) {
	cell.remove();
	galleryCreations = galleryCreations.filter((x) => String(x.id) !== String(id));
	if (els.creationsCount) els.creationsCount.textContent = `${galleryCreations.length} saved`;
	if (galleryCreations.length === 0) els.creations.classList.add('is-hidden');
	if (String(currentCreationId) === String(id)) currentCreationId = null;
}

// Load a creation into the viewer — shared by gallery card clicks and the
// share-link path. `c` is a creation row from /api/forge-gallery or
// /api/forge-creation; both return the same shape.
function openCreation(c, { scroll = true } = {}) {
	currentCreationId = c.id;
	lastJob = { prompt: c.prompt || '', imageUrls: [] };
	showResult(c.glb_url, c.prompt || 'Forged model', {
		views_used: c.views_used,
		multiview: c.multiview,
		backend: c.backend,
		tier: c.tier,
		path: c.path,
	});
	if (els.verdict) {
		for (const b of els.verdict.querySelectorAll('button')) {
			b.setAttribute('aria-pressed', String(b.dataset.outcome === c.outcome));
		}
	}
	if (scroll) els.stage.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// Open a creation from a share link. The model belongs to whoever forged it, so
// it won't be in this browser's gallery — fetch it directly by id. If the card
// is already present (the owner re-opening their own share link), reuse it.
async function openSharedCreation(shareId) {
	const card = els.creationsGrid?.querySelector(`[data-creation-id="${shareId}"]`);
	if (card) {
		card.click();
		card.scrollIntoView({ behavior: 'smooth', block: 'center' });
		return;
	}
	let creation = null;
	try {
		const res = await fetch(`/api/forge-creation?id=${encodeURIComponent(shareId)}`, {
			headers: CLIENT_HEADERS,
		});
		const data = await res.json().catch(() => ({}));
		creation = data?.creation || null;
	} catch {
		creation = null;
	}
	if (creation?.glb_url) {
		openCreation(creation);
	} else {
		showError(
			"This shared creation isn't available — it may have been removed or is still generating.",
		);
	}
}

function showError(message, { allowOverride = false } = {}) {
	stopElapsed();
	stopRateLimitCountdown();
	els.errorMessage.textContent = message;
	// The "Generate anyway" affordance only exists for the vision pre-check
	// rejection; every other error hides it so it can't leak across states.
	if (els.generateAnyway) els.generateAnyway.classList.toggle('is-hidden', !allowOverride);
	// The local-refine escape hatch belongs only to the rate-limit state.
	if (els.refineLocally) els.refineLocally.classList.add('is-hidden');
	// Lane-switch buttons belong only to the lane-failed state (showLaneFailed
	// re-reveals them after this reset).
	if (els.errorLanes) {
		els.errorLanes.classList.add('is-hidden');
		els.errorLanes.innerHTML = '';
	}
	if (els.retry) els.retry.disabled = false;
	showState('error');
}

// Every automatic backup lane is exhausted — the one moment the user may see
// an error, so it must not be a dead end. Alongside Try again, render a
// one-click button per remaining configured engine: clicking flips the picker
// (visible switch) and re-runs the same composer inputs, nothing re-entered.
function showLaneFailed(message, backends) {
	showError(message || 'That engine hit a snag mid-generation.');
	if (!els.errorLanes || !lastJob) return;
	const buttons = (backends || []).filter((id) => ENGINE_LABELS[id] || catalog?.backends?.some((b) => b.id === id));
	if (!buttons.length) return;
	for (const id of buttons) {
		const info = catalog?.backends?.find((b) => b.id === id);
		const label = ENGINE_LABELS[id] || info?.label || id;
		const btn = document.createElement('button');
		btn.type = 'button';
		btn.className = 'btn btn-ghost';
		btn.textContent = info?.free ? `Try on ${label} (free)` : `Try on ${label}`;
		btn.addEventListener('click', () => {
			if (!lastJob) return;
			// The picker flip is the affordance: the user sees exactly which engine
			// serves the retry. Fall back to a plain same-lane retry if the button
			// for that engine isn't live on this deployment.
			selectEngineByBackend(id);
			run(lastJob);
		});
		els.errorLanes.appendChild(btn);
	}
	els.errorLanes.classList.remove('is-hidden');
}

// Rate-limit state: a designed, recoverable treatment for a 429. Instead of a
// dead-end "busy, try again", we (1) show a live countdown to the reset and
// re-enable Retry automatically when it elapses, and (2) — when a model is
// already on screen — offer the local Refine path, which needs no API and never
// throttles, so the user is never fully blocked. Distinguishes a genuine quota
// hit from a temporarily-unavailable limiter (Redis degraded → fail-closed).
let rateLimitTimer = null;
function stopRateLimitCountdown() {
	if (rateLimitTimer) {
		clearInterval(rateLimitTimer);
		rateLimitTimer = null;
	}
}

function showRateLimited({ retryAfter = 10, unavailable = false, busy = false }) {
	stopElapsed();
	stopRateLimitCountdown();
	if (els.generateAnyway) els.generateAnyway.classList.add('is-hidden');

	// Offer local refinement whenever a model is already loaded — that's exactly
	// the case after the Refine button 429s, and the one moment the user most
	// wants to keep improving without waiting on the paid lane.
	const canRefineLocally = Boolean(lastShownGlb && els.viewer.getAttribute('src'));
	if (els.refineLocally) els.refineLocally.classList.toggle('is-hidden', !canRefineLocally);

	let remaining = Math.max(1, Math.ceil(retryAfter));
	const base = busy
		? 'High demand — the free 3D engines are all busy right now.'
		: unavailable
			? 'The generator is temporarily unavailable.'
			: 'You’ve hit the generation limit.';
	const tail = canRefineLocally ? ' Or refine your current model now — instant and unlimited.' : '';

	const render = () => {
		els.errorMessage.textContent =
			remaining > 0 ? `${base} Retrying is available in ${remaining}s.${tail}` : `${base} You can try again now.${tail}`;
	};
	// While counting down, Retry is disabled (it would just 429 again); it
	// re-enables the moment the window resets.
	if (els.retry) els.retry.disabled = remaining > 0;
	render();
	showState('error');

	rateLimitTimer = setInterval(() => {
		remaining -= 1;
		if (remaining <= 0) {
			stopRateLimitCountdown();
			if (els.retry) els.retry.disabled = false;
		}
		render();
	}, 1000);
}

// Run a job (text or image/multi-view). `cfg` = { prompt, imageUrls }.
async function run(cfg) {
	// Captured before the single-use payment proof is stripped — tells the upgrade
	// funnel conversion which path (pay-per-use vs. hold) closed the loop.
	const wasPaidGeneration = !!cfg.payment;
	lastJob = cfg;
	pollAbort = false;
	currentCreationId = null;
	setBusy(true);

	const isImage = Array.isArray(cfg.imageUrls) && cfg.imageUrls.length > 0;
	const isGeometry = selectedEngine.path === 'geometry';
	const isSketch = selectedEngine.path === 'sketch';
	const meshLabel = `Generating ${selectedTier} mesh`;

	// Reset the generating panel to its real starting state for this run.
	if (isSketch) {
		// The drawing IS the reference — no synthesis step, straight to geometry.
		setStepLabel('image', 'Sketch uploaded');
		setStepLabel('mesh', `Generating ${selectedTier} geometry from the sketch`);
		setStep('image', 'done');
		setStep('mesh', 'active');
		const preview = sketch.objectUrl || sketch.url;
		els.genPreview.innerHTML = preview ? '' : '<div class="shimmer" aria-hidden="true"></div>';
		if (preview) {
			const img = new Image();
			img.alt = 'Your sketch';
			img.src = preview;
			els.genPreview.appendChild(img);
		}
	} else if (isImage) {
		const n = cfg.imageUrls.length;
		setStepLabel('image', `Conditioning on ${n} ${n === 1 ? 'view' : 'views'}`);
		setStepLabel('mesh', isGeometry ? meshLabel : 'Reconstructing textured mesh');
		setStep('image', 'done');
		setStep('mesh', 'active');
		const preview = firstPreviewUrl();
		els.genPreview.innerHTML = preview ? '' : '<div class="shimmer" aria-hidden="true"></div>';
		if (preview) {
			const img = new Image();
			img.alt = 'Reference view';
			img.src = preview;
			els.genPreview.appendChild(img);
		}
	} else if (isGeometry) {
		// Geometry-first: no reference image is painted — the model emits geometry
		// straight from the prompt, so the first step is already complete.
		setStepLabel('image', 'Geometry-first — no reference image');
		setStepLabel('mesh', meshLabel);
		setStep('image', 'done');
		setStep('mesh', 'active');
		els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';
	} else {
		setStepLabel('image', 'Painting reference image');
		setStepLabel('mesh', 'Reconstructing textured mesh');
		els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';
		setStep('image', 'active');
		setStep('mesh', 'pending');
	}
	setStep('finish', 'pending');
	startElapsed();
	showState('generating');

	const label = cfg.prompt || (isImage ? 'Multi-view reconstruction' : '');

	try {
		const job = await startJob(cfg);
		if (job.creation_id) currentCreationId = job.creation_id;

		// Text→3D: the reference image resolved before the POST returned — show it.
		if (!isImage && job.preview_image_url) {
			setStep('image', 'done');
			setStep('mesh', 'active');
			const img = new Image();
			img.alt = 'Reference image';
			img.src = job.preview_image_url;
			img.onload = () => {
				els.genPreview.innerHTML = '';
				els.genPreview.appendChild(img);
			};
		}

		// The free draft lane (NVIDIA NIM) completes synchronously — the POST
		// itself returns the finished model with a null job_id. Polling that
		// null id would loop on invalid_job until the timeout, losing a result
		// that already succeeded.
		const done = job.status === 'done' && job.glb_url ? job : await pollUntilDone(job.job_id);
		if (pollAbort || !done) return; // cancelled

		// A pay-per-use proof is single-use and now redeemed on the server — drop it
		// so a later Retry/Refine of this job never replays a spent payment.
		if (lastJob) delete lastJob.payment;

		if (done.creation_id) currentCreationId = done.creation_id;
		setStep('mesh', 'done');
		setStep('finish', 'done');
		markProgressDone();
		// Prefer the poll's recorded meta; fall back to the submit response.
		showResult(
			done.glb_url,
			label || 'Forged model',
			{
				views_used: done.views_used ?? job.views_used,
				multiview: done.multiview ?? job.multiview,
				backend: done.backend ?? job.backend,
				tier: done.tier ?? job.tier,
				path: done.path ?? job.path,
			},
			{ autoSaved: !!done.creation_id },
		);
		loadGallery();
		// Geometry-first and sketch lanes have no reference image — render the
		// finished mesh itself as the creation's card visual.
		if (!(done.preview_image_url ?? job.preview_image_url)) {
			capturePoster(currentCreationId);
		}
		// Conversion: if this run followed an upgrade gate, the gated High lane just
		// produced a model — close the upgrade funnel. No-op unless a gate was shown
		// recently, and fires once per gate. Only the High tier is gated.
		if ((done.tier ?? job.tier) === 'high') {
			trackUpgradeConverted({
				feature: 'forge_high',
				path: wasPaidGeneration ? 'pay_per_use' : 'hold',
				usd: wasPaidGeneration ? Number(_highAccess?.pay_per_use?.usd) || undefined : undefined,
			});
		}
	} catch (err) {
		if (pollAbort) return;
		if (err.kind === 'unconfigured') {
			stopElapsed();
			showState('unconfigured');
			return;
		}
		// Recoverable BYOK problems — reveal + focus the key field so the user can
		// fix it and hit Retry, rather than hitting a dead end.
		if (err.kind === 'needs_key' || err.kind === 'invalid_key') {
			stopElapsed();
			els.byokRow?.classList.remove('is-hidden');
			if (els.providerKey) {
				els.providerKey.setAttribute('aria-invalid', 'true');
				els.providerKey.focus();
			}
			showError(err.message || 'Add your API key to use this engine, then retry.');
			return;
		}
		if (err.kind === 'credits') {
			stopElapsed();
			showError(err.message || 'The provider account is out of credits.');
			return;
		}
		// The reference photo failed the vision pre-check. Offer "Generate anyway"
		// so a confident user is never permanently blocked by a cautious verdict.
		if (err.kind === 'not_usable') {
			showError(err.message, { allowOverride: true });
			return;
		}
		// Rate limited (or the limiter is temporarily unavailable). Designed,
		// recoverable state with a live countdown + the local-refine escape hatch.
		if (err.kind === 'rate_limited') {
			showRateLimited({ retryAfter: err.retryAfter, unavailable: err.unavailable });
			return;
		}
		// Free lane at capacity under load — same recoverable countdown UI, framed as
		// high demand. Auto-retry lands the user in line as slots free up, and the
		// local-refine escape hatch still applies when a model is already on screen.
		if (err.kind === 'busy') {
			showRateLimited({ retryAfter: err.retryAfter, busy: true });
			return;
		}
		// High-tier $THREE gate: open the designed upsell (Get $THREE / what you hold
		// vs. need — plus the working Pay-per-use CTA) and reset to the idle composer
		// so the user can switch tier, hold, or pay.
		if (err.kind === 'hold_required') {
			stopElapsed();
			showState('empty');
			// Reflect the server's verdict back onto the composer (lock the High
			// option + the button pill/note) before opening the upsell, so the gate is
			// felt in place too — not only in the modal.
			highLocked = true;
			_highAccess = err.gate || _highAccess;
			applyHighGate();
			applyHighAffordances(err.gate);
			onGate(err.gate, gateOpts());
			return;
		}
		// A lane died mid-generation and the server has no async lane left to
		// continue on itself — but it told us which configured engines can still
		// serve this request. Hop automatically once (visible: the picker flips)
		// so a backup kicks in with zero user action; if the hop also fails,
		// surface one-click engine switches. The user never dead-ends.
		if (err.kind === 'lane_failed' && Array.isArray(err.retryBackends) && err.retryBackends.length) {
			stopElapsed();
			if (lastJob && autoLaneHops < 1 && selectEngineByBackend(err.retryBackends[0])) {
				autoLaneHops += 1;
				run(lastJob);
				return;
			}
			showLaneFailed(err.message, err.retryBackends);
			return;
		}
		// A presented pay-per-use proof was already spent — drop the stale payment so
		// Retry doesn't replay it, and re-open the pay flow for a fresh generation.
		if (err.kind === 'payment_used') {
			stopElapsed();
			if (lastJob) delete lastJob.payment;
			showState('empty');
			showError(err.message || 'That payment was already used. Pay again to generate.');
			return;
		}
		// The proof was rejected (bad/expired) before any model — drop it and surface
		// the gate's Pay-per-use path again so the user can pay cleanly.
		if (err.kind === 'payment_invalid') {
			stopElapsed();
			if (lastJob) delete lastJob.payment;
			showState('empty');
			if (err.gate) onGate(err.gate, gateOpts());
			else showError(err.message || 'That $THREE payment could not be verified.');
			return;
		}
		showError(
			err.message ||
				'Something went wrong. Try a simpler, single-subject prompt or cleaner photos.',
		);
	} finally {
		setBusy(false);
	}
}

// Gather + validate the active mode's composer inputs into a run cfg, or null
// when something's missing (focusing/flagging the offending field as a side
// effect, exactly as submit always has). Shared by the Generate button and the
// pay-per-use path so both build the job identically.
function collectComposerCfg() {
	if (mode === 'text') {
		const prompt = els.prompt.value.trim();
		if (prompt.length < 3) {
			els.prompt.focus();
			return null;
		}
		return { prompt, imageUrls: [] };
	}

	// Sketch mode — one drawing + a required prompt naming what it depicts.
	if (mode === 'sketch') {
		if (sketch.state === 'uploading') {
			els.generateLabel.textContent = 'Waiting for upload…';
			setTimeout(() => {
				if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';
			}, 1600);
			return null;
		}
		if (sketch.state !== 'uploaded' || !sketch.url) {
			const slot = sketchSlotEl();
			slot?.focus();
			slot?.classList.add('drop-target');
			setTimeout(() => slot?.classList.remove('drop-target'), 600);
			return null;
		}
		const prompt = els.sketchPrompt.value.trim();
		if (prompt.length < 3) {
			// Make the required-input contract unmissable: flag the field and tint
			// the "Required" tag until the user types a description.
			els.sketchPrompt.setAttribute('aria-invalid', 'true');
			if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'true';
			els.sketchPrompt.focus();
			return null;
		}
		return { prompt, imageUrls: [sketch.url] };
	}

	// Image / multi-view mode.
	if (slots.some((s) => s.state === 'uploading')) {
		els.generateLabel.textContent = 'Waiting for uploads…';
		setTimeout(() => {
			if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';
		}, 1600);
		return null;
	}
	const urls = uploadedUrls();
	if (urls.length === 0) {
		const first = slotEl(0);
		first?.focus();
		first?.classList.add('drop-target');
		setTimeout(() => first?.classList.remove('drop-target'), 600);
		return null;
	}
	return { prompt: els.imagePrompt.value.trim(), imageUrls: urls };
}

function submit() {
	// Platform-keyed High is a $THREE holder perk. The Generate button is disabled
	// when locked, but a keyboard submit (⌘↵) can still reach here — open the upsell
	// (with the working Pay-per-use path) instead of firing a request the server will
	// gate. BYOK High is exempt, so highTierNeedsPass() lets it through untouched.
	if (highTierNeedsPass() && highLocked) {
		if (_highAccess) onGate(_highAccess, gateOpts());
		else reflectHighAccess('high');
		return;
	}
	const cfg = collectComposerCfg();
	// A fresh user-initiated generation resets the automatic lane-hop budget —
	// the single silent hop belongs to one submission, never accumulates.
	autoLaneHops = 0;
	if (cfg) run(cfg);
}

// Options handed to the gate modal / in-place lock so their "Pay per generation"
// CTA actually works: pay $THREE for one High generation, then run the current
// composer inputs with the settled proof attached.
function gateOpts() {
	return { onPayPerUse: (pay) => payThenGenerate(pay) };
}

// The consumption lever, end to end: price comes from the gate's pay_per_use (or
// the resolved access), the user pays $THREE through the designed modal, and the
// generation re-fires immediately with { paymentId, refId } so the server's gate
// is satisfied per use. No-op if the composer inputs are incomplete (the field is
// focused) or the user cancels the payment.
async function payThenGenerate(pay) {
	const usd = Number(pay?.usd) || Number(_highAccess?.pay_per_use?.usd) || 0;
	if (!(usd > 0)) return;
	const cfg = collectComposerCfg();
	if (!cfg) return;
	// Ensure the job runs at High (the tier the payment buys) even if the click
	// came from the in-place lock before any submit.
	if (selectedTier !== 'high') selectTier('high');
	const result = await payForHighGeneration({ usd });
	if (!result?.ok) return; // cancelled or failed — the modal explained why
	run({ ...cfg, payment: { paymentId: result.paymentId, refId: result.refId } });
}

// Wiring ----------------------------------------------------------------------

els.viewer.addEventListener('error', () => {
	if (els.viewerShell) {
		els.viewerShell.classList.add('has-load-error');
		els.viewerShell.classList.remove('is-loading');
	}
});
// Retry a failed GLB fetch in place — a transient network blip on the file (the
// common cause) shouldn't dead-end at download-only. Clearing then re-setting src
// on the next frame forces model-viewer to refetch the same URL.
document.getElementById('viewer-retry')?.addEventListener('click', () => {
	const src = els.viewer.getAttribute('src');
	if (!src) return;
	els.viewerShell?.classList.remove('has-load-error');
	els.viewerShell?.classList.add('is-loading');
	els.viewer.setAttribute('src', '');
	requestAnimationFrame(() => els.viewer.setAttribute('src', src));
});
// The GLB finished painting — drop the load skeleton.
els.viewer.addEventListener('load', () => {
	els.viewerShell?.classList.remove('is-loading');
});

buildSlots();
buildViewsPips();
updateViewsCounter();

// Draw → 3D: an in-browser drawing canvas (sketch-canvas.js) as an alternative
// to uploading a photo. The exported PNG rides the SAME upload + reconstruction
// path as an uploaded reference photo — no new generation surface, just a new
// way to produce the reference image. Live today (uses whichever engine the
// image pane already resolves to); does not depend on the TripoSG-scribble
// lane the dedicated Sketch tab gates on.
els.drawViewBtn?.addEventListener('click', async () => {
	const target = firstFreeSlot();
	if (target < 0) {
		showToast('All 4 views are full — remove one first.', { type: 'info' });
		return;
	}
	const file = await openSketchCanvas();
	if (file) uploadToSlot(target, file);
});

els.drawSketchBtn?.addEventListener('click', async () => {
	const file = await openSketchCanvas();
	if (file) uploadSketch(file);
});

// Voice → prompt: dictate any of the three prompt fields instead of typing.
// Renders nothing when this browser can neither use native SpeechRecognition
// nor capture for the Riva ASR fallback (see prompt-dictation.js) — no dead
// button ships when voice input truly isn't available.
mountPromptDictation(els.promptDictateSlot, els.prompt);
mountPromptDictation(els.imagePromptDictateSlot, els.imagePrompt);
mountPromptDictation(els.sketchPromptDictateSlot, els.sketchPrompt);

els.modeSwitch.addEventListener('click', (e) => {
	const btn = e.target.closest('button[data-mode]');
	if (btn) setMode(btn.dataset.mode);
});

els.fileInput.addEventListener('change', () => {
	handleFiles(pickerTarget, els.fileInput.files);
	pickerTarget = null;
	els.fileInput.value = '';
});

els.form.addEventListener('submit', (e) => {
	e.preventDefault();
	submit();
});

// Cmd/Ctrl+Enter submits from either text box.
function submitOnModifierEnter(e) {
	if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
		e.preventDefault();
		submit();
	}
}
els.prompt.addEventListener('keydown', submitOnModifierEnter);
els.imagePrompt.addEventListener('keydown', submitOnModifierEnter);
els.sketchPrompt?.addEventListener('keydown', submitOnModifierEnter);

// Typing into the sketch prompt clears the "required" warning state.
els.sketchPrompt?.addEventListener('input', () => {
	els.sketchPrompt.removeAttribute('aria-invalid');
	if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'false';
});

els.sketchFileInput?.addEventListener('change', () => {
	const file = els.sketchFileInput.files?.[0];
	if (file) uploadSketch(file);
	els.sketchFileInput.value = '';
});

els.aspect.addEventListener('click', (e) => {
	const btn = e.target.closest('button[data-aspect]');
	if (!btn) return;
	aspectRatio = btn.dataset.aspect;
	for (const b of els.aspect.querySelectorAll('button')) {
		b.setAttribute('aria-pressed', String(b === btn));
	}
});

els.examples.addEventListener('click', (e) => {
	const chip = e.target.closest('.chip');
	if (!chip) return;
	setMode('text');
	els.prompt.value = chip.textContent.trim();
	els.prompt.focus();
	submit();
});

// Quality tier + engine + BYOK key wiring.
els.tier?.addEventListener('click', (e) => {
	const btn = e.target.closest('button[data-tier]');
	if (btn) selectTier(btn.dataset.tier);
});
els.engine?.addEventListener('click', (e) => {
	const btn = e.target.closest('button[data-engine]');
	if (btn && !btn.disabled) {
		userPickedEngine = true;
		selectEngine(btn);
	}
});
els.providerKey?.addEventListener('input', () => {
	providerKey = els.providerKey.value.trim();
	els.providerKey.removeAttribute('aria-invalid');
});

els.cancel.addEventListener('click', () => {
	pollAbort = true;
	stopElapsed();
	setBusy(false);
	if (els.categoryPicker) els.categoryPicker.hidden = true;
	destinationPicker.hide();
	showState('empty');
});

els.again.addEventListener('click', () => {
	stopRateLimitCountdown();
	if (els.categoryPicker) els.categoryPicker.hidden = true;
	destinationPicker.hide();
	showState('empty');
	if (mode === 'text') {
		els.prompt.focus();
		els.prompt.select();
	} else if (mode === 'sketch') {
		(sketch.state === 'uploaded' ? els.sketchPrompt : sketchSlotEl())?.focus();
	} else {
		slotEl(0)?.focus();
	}
});

els.retry.addEventListener('click', () => {
	if (els.retry.disabled) return; // mid-countdown; Retry re-enables at reset
	stopRateLimitCountdown();
	if (els.categoryPicker) els.categoryPicker.hidden = true;
	destinationPicker.hide();
	if (lastJob && (lastJob.prompt || (lastJob.imageUrls && lastJob.imageUrls.length))) {
		run(lastJob);
	} else {
		showState('empty');
		els.prompt.focus();
	}
});

// Rate-limit escape hatch: drop straight back to the loaded model and open the
// local Refine panel — no API, no waiting on the throttled generation lane.
els.refineLocally?.addEventListener('click', () => {
	stopRateLimitCountdown();
	showState('result');
	els.stage?.scrollIntoView({ behavior: 'smooth', block: 'start' });
	document.dispatchEvent(new CustomEvent('forge:refine-here'));
});

// Refine — re-run the same prompt/views one quality tier higher. Bumping the
// tier syncs the selector (and the tier's default engine), then replays the
// stored job, so the higher-fidelity model lands in the same viewer.
els.refine?.addEventListener('click', async () => {
	const next = nextTierAfter(currentResultTier);
	if (!next || !lastJob) return;
	selectTier(next);
	// Refining into platform-keyed High runs the same $THREE pre-flight as selecting
	// it: resolve the holder's eligibility first and open the upsell instead of firing
	// a job the server would 402. BYOK High is exempt (highTierNeedsPass() is false);
	// a transient access failure leaves highLocked false so the request proceeds and
	// the server stays the authority.
	if (highTierNeedsPass()) {
		await reflectHighAccess('high', { silent: true });
		if (highLocked) {
			if (_highAccess) onGate(_highAccess, gateOpts());
			return;
		}
	}
	run(lastJob);
});

// "Generate anyway" — re-run the same job with the vision pre-check bypassed.
els.generateAnyway?.addEventListener('click', () => {
	if (!lastJob) return;
	run({ ...lastJob, skipValidation: true });
});

if (els.verdict) {
	els.verdict.addEventListener('click', (e) => {
		const btn = e.target.closest('button[data-outcome]');
		if (!btn || !currentCreationId) return;
		const outcome = btn.dataset.outcome;
		for (const b of els.verdict.querySelectorAll('button')) {
			b.setAttribute('aria-pressed', String(b === btn));
		}
		sendFeedback({ outcome });
	});
}

if (els.categoryPicker) {
	els.categoryPicker.addEventListener('click', (e) => {
		const btn = e.target.closest('.forge-cat-btn[data-cat]');
		if (!btn || !currentCreationId) return;
		const cat = btn.dataset.cat;
		// Toggle: click the active cat again to deselect (back to 'other').
		const isActive = btn.classList.contains('active');
		els.categoryPicker.querySelectorAll('.forge-cat-btn').forEach((b) => b.classList.remove('active'));
		if (!isActive) {
			btn.classList.add('active');
			sendCategory(cat);
		} else {
			sendCategory('other');
		}
	});
}

// Downloads route through a provenance pass: fetch the GLB, stamp
// asset.generator + asset.extras (source, prompt) into the JSON chunk, and
// hand the user the stamped file. Any failure falls back to the raw provider
// file — stamping must never block a download.
els.download.addEventListener('click', async (e) => {
	sendFeedback({ downloaded: true });
	const glbUrl = els.download.href;
	if (!glbUrl || glbUrl.startsWith('blob:') || els.download.dataset.stamping) return;
	e.preventDefault();
	els.download.dataset.stamping = '1';
	els.download.setAttribute('aria-busy', 'true');
	const originalText = els.download.textContent;
	els.download.textContent = 'Preparing…';
	const filename = els.download.getAttribute('download') || 'forge.glb';
	try {
		const res = await fetch(glbUrl);
		if (!res.ok) throw new Error(`fetch ${res.status}`);
		const stamped = stampGlbAttribution(await res.arrayBuffer(), {
			prompt: els.resultLabel?.textContent || '',
		});
		const blobUrl = URL.createObjectURL(new Blob([stamped], { type: 'model/gltf-binary' }));
		const a = document.createElement('a');
		a.href = blobUrl;
		a.download = filename;
		a.click();
		setTimeout(() => URL.revokeObjectURL(blobUrl), 30_000);
	} catch {
		const a = document.createElement('a');
		a.href = glbUrl;
		a.download = filename;
		a.click();
	} finally {
		delete els.download.dataset.stamping;
		els.download.removeAttribute('aria-busy');
		els.download.textContent = originalText;
	}
});

els.cinema?.addEventListener('click', () => setCinema(!cinemaOn));

document.addEventListener('keydown', (e) => {
	if (e.key === 'Escape' && cinemaOn) {
		setCinema(false);
		return;
	}
	if (e.metaKey || e.ctrlKey || e.altKey) return;
	const active = document.activeElement;
	if (active?.tagName === 'INPUT' || active?.tagName === 'TEXTAREA' || active?.isContentEditable)
		return;
	// "/" jumps to the prompt for the current mode — the standard quick-focus.
	if (e.key === '/') {
		e.preventDefault();
		const box =
			mode === 'sketch' ? els.sketchPrompt : mode === 'image' ? els.imagePrompt : els.prompt;
		box?.focus();
		return;
	}
	if (e.key !== 'f' && e.key !== 'F') return;
	if (els.states.result.classList.contains('is-hidden')) return;
	e.preventDefault();
	setCinema(!cinemaOn);
});

if (els.forgeShareBtn) {
	els.forgeShareBtn.addEventListener('click', () => {
		const origin = location.origin;
		const prompt = els.forgeShareBtn.dataset.sharePrompt || lastJob?.prompt || '';
		const id = currentCreationId;
		const shareUrl = id ? `${origin}/forge/share/${id}` : `${origin}/forge`;
		const remixUrl = prompt
			? `${origin}/forge?prompt=${encodeURIComponent(prompt)}`
			: `${origin}/forge`;
		showSharePanel(
			{
				kind: 'forge',
				id: id || '',
				title: prompt || 'Forged creation',
				description: 'A 3D model generated with text / image → 3D on three.ws',
				shareUrl,
				remixUrl,
			},
			els.forgeShareBtn,
		);
	});
}

// Handle ?prompt= (pre-fill from a remix link) and ?share= (open a creation).
(function handleQueryParams() {
	const params = new URLSearchParams(location.search);
	const promptParam = params.get('prompt');
	const shareParam = params.get('share');
	if (promptParam && els.prompt) {
		setMode('text');
		els.prompt.value = decodeURIComponent(promptParam).slice(0, 300);
		els.prompt.focus();
	}
	if (shareParam) {
		window.__forgeShareId = shareParam;
	}
})();

// Hooks for the companion modules (forge-dropzone.js, forge-showcase.js) —
// a CustomEvent contract keeps them decoupled from this file's internals.

// Images captured anywhere on the page (clipboard paste, page-level drop).
// In sketch mode a single image becomes the sketch; otherwise we switch to
// photo mode and distribute into free view slots.
document.addEventListener('forge:add-images', (e) => {
	const files = Array.isArray(e.detail?.files) ? e.detail.files : [];
	if (!files.length) return;
	if (mode === 'sketch' && files.length === 1) {
		uploadSketch(files[0]);
		return;
	}
	if (mode !== 'image') setMode('image');
	handleFiles(null, files);
});

// A community-showcase card asks to open its creation in the main viewer, so
// the full result bar (download, share, stylize, optimize, split) works on it.
document.addEventListener('forge:open-creation', (e) => {
	const creation = e.detail?.creation;
	if (creation?.glb_url) openCreation(creation);
});

// Build the quality/engine controls from the live catalog (tiers, backends,
// cost/time matrix). Falls back silently to the defaults if it can't load.
loadCatalog();

// Surface the $THREE holder gate on the High control up front (pill + note),
// independent of the catalog so the affordance lands even on older deploys.
reflectHighButtonAccess();

// Forge-local wallet connect (Part A): wire the connect chip + auto-connect a trusted
// wallet so a connected holder's High unlock + free-quota perk surface with no reload.
// Re-read the gate + perk line whenever the wallet connects or disconnects.
initWalletButton();
updatePerkLine();
window.addEventListener('wallet:changed', () => {
	reflectHighButtonAccess();
	if (selectedTier === 'high') reflectHighAccess('high');
	updatePerkLine();
});

// Surface any previously forged models for this browser on load.
loadGallery().then(() => {
	const shareId = window.__forgeShareId;
	if (shareId) openSharedCreation(shareId);
});