Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

alphabet.gno

package nsview

import (
	"strings"

	"gno.land/p/nt/ufmt/v0"
)

/*
A HAND-DRAWN ALPHABET, STORED ONCE.

WHY THIS EXISTS. Every renderer that shows these cards — wallets,
marketplaces, block explorers — puts the SVG in a sandbox with no
network. A web font therefore never loads; it silently substitutes, and
the display lettering the mockups were designed around turns into
whatever that particular viewer happens to default to. Only the generic
families (serif, sans-serif, monospace) can be relied on, and none of
them is a marker pen.

The only way to get identical letterforms on every device is to ship the
letters themselves. These are strokes, not outlines: a path with a round
cap and a thick stroke looks like a pen, costs a fraction of the data an
outline font would, and scales without a second set of hinting.

THESE LETTERFORMS ARE OUR OWN. They are not traced from, derived from, or
measured against any existing typeface. A typeface is somebody's design
and often somebody's licensed asset; drawing our own marker capitals is
both cheaper and the only version we are entitled to put on chain
permanently. The house rule elsewhere on this project is "original art in
the spirit of the thing", and a font is art.

WHAT IT COSTS. Storage is 100 ugnot a byte and permanent, so the
encoding is deliberately dense rather than readable: each point is two
characters, each stroke is a run of points, strokes are separated by "|".
The whole alphabet — twenty-six letters, ten digits, and the punctuation
this project actually uses — is well under a kilobyte. An outline font
would have been tens of kilobytes and unreadable besides.

THE GRID. Ten wide by fourteen tall, origin top-left, so a glyph reads
directly as coordinates: "0d" is the bottom-left corner and "47" is the
middle. x never exceeds 9, so it is always one digit; y reaches 13, so
10..13 are written a..d.
*/

// glyph returns the stroke encoding for one character, or "" for
// anything unknown — an unknown character draws nothing rather than a
// box, because this markup lands inside a token that other people's
// software renders and a missing letter is better than a wrong one.
func glyph(c byte) string {
	switch c {
	// Generated from a readable point table rather than typed by
	// hand: forty glyphs of paired coordinate characters is precisely
	// the job where one stray character shifts a whole letter by one and
	// nobody spots it until it is on chain forever.
	case 'A':
		return "0d409d|2878"
	case 'B':
		return "000d|006206|06790d"
	case 'C':
		return "824014194d8b"
	case 'D':
		return "000d|00737a0d"
	case 'E':
		return "80000d8d|0666"
	case 'F':
		return "80000d|0666"
	case 'G':
		return "824014194d8b8757"
	case 'H':
		return "000d|909d|0696"
	case 'I':
		return "2070|404d|2d7d"
	case 'J':
		return "707a4d1a"
	case 'K':
		return "000d|8007|359d"
	case 'L':
		return "000d8d"
	case 'M':
		return "0d1047809d"
	case 'N':
		return "0d009d90"
	case 'O':
		return "4014194d898440"
	case 'P':
		return "0d00727507"
	case 'Q':
		return "4014194d898440|6a9d"
	case 'R':
		return "0d00727507|379d"
	case 'S':
		return "824013678a4d1b"
	case 'T':
		return "0090|404d"
	case 'U':
		return "00094d8980"
	case 'V':
		return "004d90"
	case 'W':
		return "002d457d90"
	case 'X':
		return "009d|900d"
	case 'Y':
		return "004790|474d"
	case 'Z':
		return "00900d9d"
	case '0':
		return "4014194d898440|2974"
	case '1':
		return "23404d|2d7d"
	case '2':
		return "1340830d9d"
	case '3':
		return "11508446|46895d1b"
	case '4':
		return "7d700999"
	case '5':
		return "80101666895d1b"
	case '6':
		return "7140151a5d8a5718"
	case '7':
		return "00903d"
	case '8':
		return "4613407346194d7946"
	case '9':
		return "8647144084895d2c"
	case '*':
		return "424a|1479|7419"
	case '-':
		return "1787"
	case '.':
		return "4c4d"
	case '!':
		return "4049|4c4d"
	case '?':
		return "1340734749|4c4d"
	case '\'':
		return "4043"
	case ' ':
		return ""
	}
	return ""
}

const (
	glyphW  = 10 // grid width of one glyph
	glyphH  = 14 // grid height, top to bottom
	glyphAd = 12 // advance: glyph width plus the gap to the next one
)

// hexish decodes one coordinate character. Digits are themselves; a..d
// carry 10..13, which is the only reason y can exceed nine in two
// characters.
func hexish(c byte) int {
	if c >= '0' && c <= '9' {
		return int(c - '0')
	}
	if c >= 'a' && c <= 'd' {
		return int(c-'a') + 10
	}
	return -1
}

/*
MarkerText draws a line of text as stroked paths.

`size` is the CAP HEIGHT in user units, not an em size: it is the height
of a capital letter, which is the measurement anybody positioning this by
eye is actually thinking in.

`x` is the left edge and `y` is the TOP of the capitals, matching how the
rest of this file positions things and unlike SVG's own text baseline,
which is a trap when mixing the two.

The jitter is what makes it read as a pen rather than a plotter. It is
derived from the character and its position, so it is stable: the same
string renders identically on every read, which matters because these
cards are regenerated constantly and a letter that wobbled between reads
would look like a rendering fault.
*/
func MarkerText(s string, x, y, size int, colour string, weight int) string {
	if s == "" || size <= 0 {
		return ""
	}
	if weight <= 0 {
		weight = 1 + size/7
	}
	var out strings.Builder
	out.WriteString(ufmt.Sprintf(
		`<g fill="none" stroke="%s" stroke-width="%d" stroke-linecap="round" stroke-linejoin="round">`,
		colour, weight))

	up := strings.ToUpper(s)
	for i := 0; i < len(up); i++ {
		enc := glyph(up[i])
		if enc == "" {
			continue
		}
		ox := x + i*glyphAd*size/glyphH
		out.WriteString(strokes(enc, ox, y, size, i))
	}
	out.WriteString(`</g>`)
	return out.String()
}

// strokes turns one glyph's encoding into path elements at a position.
func strokes(enc string, ox, oy, size, idx int) string {
	var out strings.Builder
	for _, run := range strings.Split(enc, "|") {
		d := ""
		n := 0
		for j := 0; j+1 < len(run); j += 2 {
			gx := hexish(run[j])
			gy := hexish(run[j+1])
			if gx < 0 || gy < 0 {
				continue // a space inside an encoding is padding, not a point
			}
			// Scale from the grid to cap height, then nudge. The nudge is
			// at most one unit and comes from a fixed mix of the glyph
			// index and the point index, so it never changes between reads.
			px := ox + gx*size/glyphH
			py := oy + gy*size/glyphH
			px += wobble(idx*7 + j*3)
			py += wobble(idx*5 + j*11 + 1)
			if n == 0 {
				d += ufmt.Sprintf("M%d %d", px, py)
			} else {
				d += ufmt.Sprintf("L%d %d", px, py)
			}
			n++
		}
		if n > 1 {
			out.WriteString(`<path d="` + d + `"/>`)
		} else if n == 1 {
			// A single point would draw nothing without a round cap on a
			// zero-length path, which not every renderer honours. Give it
			// a hair of length instead.
			out.WriteString(`<path d="` + d + `l1 0"/>`)
		}
	}
	return out.String()
}

// wobble is a tiny deterministic offset in the range -1..1. Not random:
// the cards are regenerated on every read, and anything genuinely random
// would make the lettering shimmer.
func wobble(seed int) int {
	return (seed*2654435761)%3 - 1
}

// MarkerWidth is what MarkerText will occupy, so a caller can centre it.
// Counts every character including the ones that draw nothing, because a
// space still advances.
func MarkerWidth(s string, size int) int {
	if s == "" {
		return 0
	}
	return len(s) * glyphAd * size / glyphH
}

// MarkerCentred draws text centred on cx, which is what almost every
// caller here wants and what the SVG text-anchor attribute would have
// done for them if a font had been available.
func MarkerCentred(s string, cx, y, size int, colour string, weight int) string {
	return MarkerText(s, cx-MarkerWidth(s, size)/2, y, size, colour, weight)
}

gnomod.toml

module = "gno.land/r/nym-mnsrehearsal001/nsview/v1"
gno = "0.9"

[addpkg]
  creator = "g1lh4rrf9pq9k9tvka9p6vwhyv70e4h09szap6zu"
  height = 452712
  max_deposit = "40000000ugnot"

ledgerart.gno

package nsview

import (
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"strings"
	"time"

	"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
	"gno.land/r/nym-mnsrehearsal001/nsnft/v1"
	"gno.land/r/nym-mnsrehearsal001/nsskin/v1"
)

/*
THIS REALM DRAWS THE NAMES IN WALLETS.

A wallet asks the LEDGER, nsnft, for TokenURI and TokenMetadata, because
the collection id names it. nsnft can never change, so it does not draw:
it holds a Renderer handed to it by the one view realm it has approved,
and that realm is this one. Swapping the art is deploying a new nsview and
approving it on nsnft (a timelocked change), nothing more.

The renderer's methods run with THIS realm's authority (gno's
declaring-realm borrow), so drawing for the ledger can read anything and
write nothing of the ledger's. This realm holds no state worth writing
anyway; selfPath is set once, at init.
*/

// selfPath is this realm's path without the chain domain, for links to
// its own gnoweb pages. Set at init, because inside a renderer call the
// realm context belongs to whoever asked, not to this realm.
var selfPath string

type ledgerArt struct{}

// TokenImage is nsview's TokenURI: the full card, drawn now.
func (ledgerArt) TokenImage(tid string) string { return TokenURI(tid) }

func (ledgerArt) TokenMetadata(tid string) string { return tokenMetadata(tid) }

func init(cur realm) {
	selfPath = strings.TrimPrefix(cur.PkgPath(), runtime.ChainDomain())
	// Register only when this realm is the approved one. Registering
	// unconditionally would make deploying a NEW view generation fail
	// until its approval had cleared the timelock; this way it deploys,
	// and RegisterWithLedger finishes the job once it is approved.
	if nsnft.RendererPath() == cur.PkgPath() {
		nsnft.RegisterRenderer(cross(cur), ledgerArt{})
	}
}

// RegisterWithLedger hands the ledger this realm's renderer. Anyone may
// call it: it only ever registers THIS realm's own drawing, and the ledger
// refuses unless this realm is the one it has approved.
func RegisterWithLedger(cur realm) {
	// This realm has no banker and no way to return coins.
	if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) > 0 {
		panic("nsview: this call takes no payment")
	}
	nsnft.RegisterRenderer(cross(cur), ledgerArt{})
}

/*
tokenMetadata is the camelCase JSON Adena reads: name, description,
externalUrl, attributes of {traitType, value}. Everything in it is read
from the registry at the moment of asking, like the card, so a renewal or
a sale shows up without anybody writing anything.
*/
func tokenMetadata(tid string) string {
	label, dom := splitTokenID(tid)
	if label == "" || dom == "" || !nsdata.NameExists(label, dom) {
		return `{"name":"` + escapeJSON(tid) + `","description":"A name on the Meme Name Service.","attributes":[]}`
	}
	_, registered, expires, _, frozen, paid := nsdata.GetNameInfo(label, dom)
	status, _ := statusFields(expires, frozen)
	tier := "paid"
	if !paid {
		tier = "free tier"
	}
	skin := "none"
	if worn := nsskin.SkinOnName(label, dom); worn != "" && nsskin.ArtForName(label, dom) != "" {
		skin = worn
	}
	out := `{"name":"` + escapeJSON(label+"*"+dom) + `",` +
		`"description":"A name on the Meme Name Service. You own a word now. Renew it, or somebody else will.",`
	if selfPath != "" {
		out += `"externalUrl":"` + escapeJSON("https://"+runtime.ChainDomain()+selfPath+":"+label+"*"+dom) + `",`
	}
	out += `"attributes":[` +
		attr("Domain", "*"+dom) + `,` +
		attr("Length", strconv.Itoa(len(label))) + `,` +
		attr("Status", strings.ToLower(status)) + `,` +
		attr("Registered", time.Unix(registered, 0).UTC().Format("2006-01-02")) + `,` +
		attr("Expires", time.Unix(expires, 0).UTC().Format("2006-01-02")) + `,` +
		attr("Tier", tier) + `,` +
		attr("Skin", skin) + `]}`
	return out
}

func attr(k, v string) string {
	return `{"traitType":"` + escapeJSON(k) + `","value":"` + escapeJSON(v) + `"}`
}

func escapeJSON(s string) string {
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c == '"':
			b.WriteString(`\"`)
		case c == '\\':
			b.WriteString(`\\`)
		case c < 0x20:
			const hex = "0123456789abcdef"
			b.WriteString(`\u00`)
			b.WriteByte(hex[c>>4])
			b.WriteByte(hex[c&0xf])
		default:
			b.WriteByte(c)
		}
	}
	return b.String()
}

nameplate.gno

package nsview

import (
	"strings"
	"time"

	"gno.land/p/nt/ufmt/v0"
)

/*
THE NAMEPLATE — the name, the asterisk and the expiry, composited over
somebody else's artwork.

WHY IT IS THE CONTRACT'S JOB AND NOT THE ARTIST'S. A skin is a picture
somebody else drew. If they also controlled the lettering they could
omit it, cover it, shrink it to nothing, or write different text — and a
card that does not say which name it is, is not a name card. So the
artist chooses three things from short lists (face, position, ink) and
the contract does the rest.

THE ASTERISK IS DRAWN, NEVER TYPED. Every typeface sets `*` small and
lifted to cap height, because in running text it is a footnote marker.
Here it is a letter — it is the entire brand — so it is drawn at the
weight of the type around it, at the x-height of the lowercase letters
beside it, and centred on their optical band. Typing it produces a small
mark floating above the words, which is exactly what it is for and
exactly wrong here.

ONE ASTERISK IN ALL THREE FACES, cut square. Three shapes were tried —
tapered for serif, square for sans, square and lighter for mono — and the
lightest square one won outright, so the other two are gone. It is the
mark, not a glyph borrowed from whatever face happens to be set; making
it agree with the type was solving a problem nobody had.

A REALM CANNOT MEASURE TEXT, and that used to shape the whole algorithm.
It matters much less now: the widths below are real per-character
metrics rather than one average, and textLength makes the renderer honour
them. See the long note in NameplateSVG.

This file is the single source of truth for the geometry. Anything that
previews a card — the site, a mockup, a shop listing — must reproduce
these numbers exactly or it is showing something that will not ship.
tools/diff-nameplate.sh enforces that against the site's mirror.
*/

// The card is 400x400 and the name may use all but a margin either side.
const (
	plateW      = 400
	plateMargin = 30
	plateAvail  = plateW - 2*plateMargin // 340

	plateMaxSize = 56 // any larger and a two-letter name dominates the art

	// A LAST-RESORT floor, not a readability one, and the difference is
	// a bug worth recording. This was 18 — "any smaller and it stops
	// being readable in a thumbnail" — which is a fine aspiration and an
	// impossible guarantee. maxLabelLen is 63, and sixty-three m's need
	// about five pixels to fit a 400px card. The clamp won that argument
	// and the name ran off the edge, inside somebody else's wallet.
	//
	// Fitting beats legibility because they are not comparable failures:
	// a small name is small, a name that leaves the card is broken. And
	// there is no third option — the card has to show the WHOLE name, so
	// truncating it is not available. So the solver goes as small as the
	// width demands and this is only the point below which a glyph would
	// round away to nothing whatever we did. In practice it never binds:
	// the longest legal name still solves above it.
	plateMinSize = 4
)

/*
GLYPH WIDTHS, per generic family, in thousandths of the type size.

This replaced a single average-width ratio per family, and the reason is
worth keeping, because the average was not merely imprecise — it put
names visibly off centre, by an amount that depended on which letters
somebody had picked.

A serif "l" is 278 and a serif "m" is 833. One number cannot stand in for
both. The old ratio was 560 against a true average of 488, so a name made
of narrow letters — tessellation, say — came out forty per cent too wide,
and because the asterisk is placed using that figure, the whole name slid
sideways by half the error. That is exactly what showed up on the proof
sheet: tessellation pushed right, cosmos slightly left, say*gm slightly
right. Monospace was never off, because there one number IS the answer
and 600 was within two thousandths of it.

Only the three generic families are offered. Every renderer that shows
these puts the SVG in a sandbox with no network, so a web font never
loads — it silently substitutes, and the card becomes whatever that
viewer happens to default to. serif, sans-serif and monospace are the
only families that resolve everywhere. These are the metrics of the bold
faces they resolve to almost everywhere; textLength covers the rest.

Three digits per character, in the order of plateOrder. Names are
[a-z0-9-] — lowercase is enforced at registration — so that is the whole
alphabet this has to cover.
*/
const plateOrder = "abcdefghijklmnopqrstuvwxyz0123456789-"

const (
	plateWSerif = "500556444556444333500556278333556278833" +
		"556500556556444389333556500722500500444" +
		"500500500500500500500500500500333"

	plateWSans = "556611556611556333611611278278556278889" +
		"611611611611389556333611556778556556500" +
		"556556556556556556556556556556333"

	plateWMono = "602602602602602602602602602602602602602" +
		"602602602602602602602602602602602602602" +
		"602602602602602602602602602602602"
)

func plateWidths(face string) (tbl string, fallback int) {
	switch face {
	case "mono":
		return plateWMono, 602
	case "serif":
		return plateWSerif, 488
	default:
		return plateWSans, 538
	}
}

func plateFamily(face string) string {
	switch face {
	case "mono":
		return "monospace"
	case "serif":
		return "serif"
	default:
		return "sans-serif"
	}
}

// plateAdvance sums a string's width in thousandths of the type size.
// A character outside the alphabet falls back to the family's average
// rather than to zero: a name that somehow escapes the pattern should
// lay out slightly wrong, not collapse into the asterisk.
func plateAdvance(s, face string) int {
	tbl, fallback := plateWidths(face)
	total := 0
	for i := 0; i < len(s); i++ {
		idx := strings.IndexByte(plateOrder, s[i])
		if idx < 0 || (idx*3+2) >= len(tbl) {
			total += fallback
			continue
		}
		total += int(tbl[idx*3]-'0')*100 + int(tbl[idx*3+1]-'0')*10 + int(tbl[idx*3+2]-'0')
	}
	return total
}

/*
plateSize solves for the largest type size whose width fits.

The asterisk occupies a column of its own, 0.86 of the type size wide,
which is why it is in the denominator rather than added afterwards: the
letters and the asterisk have to shrink together or the proportions
drift as a name gets longer. That is the whole reason this is one
calculation instead of two.

`adv` is the summed advance of both halves, in thousandths.
*/
func plateSize(adv int, face string) int {
	if adv < 1 {
		adv = 1
	}
	// size * (adv/1000 + 0.86) <= avail
	denom := adv + 860
	size := plateAvail * 1000 / denom
	if size > plateMaxSize {
		size = plateMaxSize
	}
	if size < plateMinSize {
		size = plateMinSize
	}
	return size
}

/*
GEOMETRY, all derived from the type size so every proportion holds at
every length.

	capH       0.70 * size   the height of an uppercase letter
	xH         0.52 * size   the height of a lowercase e — no ascender
	starR      0.26 * size   half the x-height, so the asterisk is exactly
	                         as tall as an "e" and not as tall as a "b".
	                         Matching the cap height made it the tallest
	                         thing on the line; names are lowercase, so the
	                         x-height is what the eye reads as "letter
	                         height" and anything above it reads as a mark
	starArm    0.104 * size  the asterisk's own stroke. This is the weight a
	                         MONOSPACED face sets an asterisk at — lighter
	                         than the letters around it, because every glyph
	                         there has to fit one fixed width — and it is
	                         the one that read best of the three that were
	                         tried, so it is now the weight in every face
	outline    0.05 * size   the border, on the letters AND the asterisk,
	                         the same on both because a border that differs
	                         between them looks like a mistake rather than
	                         a choice. Thin enough to be a contrast device
	                         and not a second typeface: a heavy outline
	                         thickens every stem and the name stops looking
	                         like the face it was set in
*/
func plateGeom(size int) (capH, xH, starR, starArm, outline int) {
	capH = size * 70 / 100
	xH = size * 52 / 100
	starR = xH / 2
	starArm = size * 104 / 1000
	outline = size * 5 / 100
	if outline < 1 {
		outline = 1
	}
	if starArm < 2 {
		starArm = 2
	}
	return
}

/*
THE SIX RAYS, as unit vectors in thousandths.

An asterisk is six rays at sixty degrees. In SVG's coordinate system y
grows downward, so "up" is negative. cos30 is 866 and cos60 is 500.

Listed in CLOCKWISE SCREEN ORDER starting from straight up, which
starPoly depends on: it walks them in sequence to trace the outline, and
any other order produces a self-intersecting polygon.
*/
var starRays = [6][2]int{
	{0, -1000}, {866, -500}, {866, 500},
	{0, 1000}, {-866, 500}, {-866, -500},
}

/*
starPoints returns the asterisk's outline, IN HUNDREDTHS OF A PIXEL.

WHY IT IS AN OUTLINE AND NOT THREE CROSSING LINES. The border has to be
the same thickness the whole way round, exactly as it is on the letters,
and drawing the shape twice at two stroke widths cannot give that.

A wider stroke offsets a line sideways, but where two arms MEET the two
wide strokes overlap and fill the valley between them in, so the border
is fat at the hub. At the tips it only extends by its own half-width, so
it is thin there. That is not a rounding error, it is the wrong tool.
Widening a stroke is not the same operation as offsetting a boundary, and
they only agree on a shape with no concave corners. An asterisk is
nothing but concave corners.

The letters do not have this problem because a renderer strokes a glyph's
OUTLINE, which is a true offset — every point of the border ends up the
same distance from the edge. So the asterisk gets an outline too, and
then exactly the same two passes the text gets.

WHY HUNDREDTHS, AND NOT WHOLE PIXELS. Because whole pixels made the six
arms different widths, which is worse than the problem above and was
plainly visible. The arm half-width is arm/2, and at the sizes this
actually renders arm is 5, so the half-width is 2.5 — a number a pixel
grid cannot hold. Worse, each direction lost a DIFFERENT amount to
truncation: the vertical arm computed 1000*5/2000 = 2 exactly, while a
diagonal computed (500*5/2000, 866*5/2000) = (1,2), whose length is
2.236. So four arms came out twelve per cent fatter than the other two,
and every arm was a fifth thinner than intended.

SVG coordinates are not integers, so the fix is simply to stop rounding
to them. Everything below is computed in hundredths of a pixel and
printed with two decimals, which brings the six half-widths to 2.500 and
2.496 — a spread of 0.16% instead of 12%.

THE GEOMETRY. Each ray is a rectangle of half-width arm/2 out to radius
r, cut square at the tip. Where two adjacent rays meet, their inner edges
cross on the bisector — and for rays sixty degrees apart that crossing
sits at radius exactly arm, which falls out of the algebra rather than
being tuned. Eighteen points: two tip corners and one valley per ray,
walked in the ray order above.
*/
func starPoints(cx, cy, r, arm int) [18][2]int {
	var out [18][2]int
	for i := 0; i < 6; i++ {
		u := starRays[i]
		n := starRays[(i+1)%6]
		// The perpendicular, pointing toward the NEXT ray.
		px, py := -u[1], u[0]
		// u is in thousandths and the result is in hundredths, so
		// u*r/1000*100 collapses to u*r/10. Likewise p/1000 * arm/2 * 100
		// is p*arm/20.
		ox, oy := cx*100+u[0]*r/10, cy*100+u[1]*r/10
		dx, dy := px*arm/20, py*arm/20
		out[i*3] = [2]int{ox - dx, oy - dy}   // tip, trailing corner
		out[i*3+1] = [2]int{ox + dx, oy + dy} // tip, leading corner
		// The valley, on the bisector at radius arm. |u+n| is 1732 for
		// rays sixty degrees apart, so this normalises it.
		out[i*3+2] = [2]int{
			cx*100 + (u[0]+n[0])*arm*100/1732,
			cy*100 + (u[1]+n[1])*arm*100/1732,
		}
	}
	return out
}

// hundredths formats a coordinate held in hundredths of a pixel.
//
// Two things it must not do, both found the hard way. The sign is peeled
// off first, because integer division truncates toward zero on BOTH
// halves and -250 would otherwise print as "-2.-50". And the fraction is
// assembled a digit at a time rather than with "%02d", because ufmt does
// not implement the zero-padding flag — it silently printed 68.0 where
// two digits were asked for, which the mirror diff caught as drift.
func hundredths(v int) string {
	sign := ""
	if v < 0 {
		sign, v = "-", -v
	}
	f := v % 100
	return ufmt.Sprintf("%s%d.%d%d", sign, v/100, f/10, f%10)
}

func starPoly(cx, cy, r, arm int) string {
	pts := starPoints(cx, cy, r, arm)
	var b strings.Builder
	for i := 0; i < len(pts); i++ {
		if i > 0 {
			b.WriteString(" ")
		}
		b.WriteString(hundredths(pts[i][0]))
		b.WriteString(",")
		b.WriteString(hundredths(pts[i][1]))
	}
	return b.String()
}

// starSVG draws the asterisk in the two passes the lettering uses:
// border first at twice the width, ink over it. No face argument — one
// asterisk in every face, see the note at the top of the file.
func starSVG(cx, cy, r, arm, outline int, ink, edge string) string {
	pts := starPoly(cx, cy, r, arm)
	return ufmt.Sprintf(
		`<polygon points="%s" fill="%s" stroke="%s" stroke-width="%d" stroke-linejoin="round"/>`+
			`<polygon points="%s" fill="%s"/>`,
		pts, edge, edge, outline*2, pts, ink)
}

/*
NameplateSVG composites the name, the asterisk and the expiry over
whatever is already on the card.

  face   "mono" | "serif" | "sans"
  pos    "top" | "middle" | "bottom"
  light  true  = white letters with a black border
         false = black letters with a white border

Only two ink pairs exist, and that is not a limitation waiting to be
lifted. Both read on every background there is; a free colour choice does
not, and mid-grey lettering on a mid-grey drawing is exactly what
somebody will pick.
*/
// `now` is deliberately absent from the signature. Nothing here counts
// down, so nothing here needs the clock — see the note on the expiry.
func NameplateSVG(label, domain, face, pos string, light bool, expires int64) string {
	lAdv := plateAdvance(label, face)
	dAdv := plateAdvance(domain, face)
	size := plateSize(lAdv+dAdv, face)
	_, xH, starR, starArm, outline := plateGeom(size)
	fam := plateFamily(face)

	ink, edge := "#ffffff", "#0b0d10"
	if !light {
		ink, edge = "#0b0d10", "#ffffff"
	}

	var baseY, dateY int
	switch pos {
	case "top":
		baseY, dateY = 96, 356
	case "bottom":
		baseY, dateY = 322, 96
	default:
		baseY, dateY = 212, 356
	}

	/*
		THE TWO HALVES ARE ANCHORED TO THE ASTERISK, AND THEIR WIDTHS ARE
		DICTATED RATHER THAN GUESSED.

		Two faults came out of the same root, and the same pair of
		mechanisms closes both.

		The GAP before the asterisk: the width was estimated, and the
		estimate placed both the end of the label and the asterisk, so any
		error between the two opened up as a hole.

		The whole name sitting OFF CENTRE: the composition is centred on
		x0, computed from that same estimate. Work it through and the
		asterisk lands at 200 + (lw-dw)/2 when it needs to land at
		200 + (trueLw-trueDw)/2. The error is half the difference of the
		two errors — so a long narrow label against a short domain slid
		right, and the reverse slid left. Exactly what the proof sheet
		showed.

		FIRST, the halves are anchored TO the asterisk — label right,
		domain left — which hands the placement of the glyphs relative to
		it back to the renderer. That kills the gap outright.

		SECOND, and this is what makes the centring exact: textLength. SVG
		lets an element declare its own advance width and the renderer
		fits the text to it. So lw and dw stop being predictions and
		become instructions: whatever font the viewer actually resolved,
		the label occupies exactly lw and the domain exactly dw, and the
		arithmetic that centres them is true by construction rather than
		by luck.

		lengthAdjust="spacing", never "spacingAndGlyphs" — it moves the
		letters apart, it does not squeeze their shapes. With the real
		width table above, the adjustment on the usual fonts is nil, and
		on a substituted one it is a fraction of a pixel of tracking.
		Distorting glyphs to save a rounding error would be a bad trade.

		The one case left is a single-character half on a substituted
		font: there are no inter-glyph gaps, so "spacing" has nothing to
		adjust. The table is exact for one character by definition, so
		this only misses when the font ALSO substituted, and then by a few
		pixels. Left deliberately — the alternative distorts the glyph.
	*/
	lw := lAdv * size / 1000
	dw := dAdv * size / 1000
	starCol := size * 86 / 100
	total := lw + starCol + dw
	x0 := (plateW - total) / 2

	starCX := x0 + lw + starCol/2
	// Centred on the x-height, so the asterisk sits in the same optical
	// band as the lowercase letters either side of it.
	starCY := baseY - xH/2
	labelX := starCX - starCol/2
	domainX := starCX + starCol/2

	var b strings.Builder

	// One pass per layer. Border first, ink second, so the border sits
	// behind the letter rather than eating half of it. textLength goes on
	// every pass, or the two would disagree about where the letters are.
	const half = `<text x="%d" y="%d" text-anchor="%s" textLength="%d" lengthAdjust="spacing"` +
		` fill="none" stroke="%s" stroke-width="%d" stroke-linejoin="round">%s</text>`
	const fill = `<text x="%d" y="%d" text-anchor="%s" textLength="%d" lengthAdjust="spacing"` +
		` fill="%s">%s</text>`

	b.WriteString(ufmt.Sprintf(`<g font-family="%s" font-size="%d" font-weight="bold">`, fam, size))
	b.WriteString(ufmt.Sprintf(half, labelX, baseY, "end", lw, edge, outline*2, esc(label)))
	b.WriteString(ufmt.Sprintf(half, domainX, baseY, "start", dw, edge, outline*2, esc(domain)))
	b.WriteString(ufmt.Sprintf(fill, labelX, baseY, "end", lw, ink, esc(label)))
	b.WriteString(ufmt.Sprintf(fill, domainX, baseY, "start", dw, ink, esc(domain)))
	b.WriteString(`</g>`)

	b.WriteString(starSVG(starCX, starCY, starR, starArm, outline, ink, edge))

	/*
		THE EXPIRY, ON EVERY CARD, AS A DATE AND NOTHING ELSE.

		The ordinary card alternates a date with a countdown and carries a
		long note about which one a still frame must land on. A skinned
		card skips the problem: a marketplace thumbnail of "412 days left"
		is a number that was true once and is a lie afterwards, while a
		date is true forever. One sentence, always the same one.
	*/
	dateSize := 15
	// Same format the ordinary card already uses for an expiry, so a
	// skinned card and a plain one do not disagree about how a date looks.
	txt := "EXPIRES ON " + strings.ToUpper(time.Unix(expires, 0).UTC().Format("Jan 2, 2006"))
	b.WriteString(ufmt.Sprintf(
		`<g font-family="monospace" font-size="%d" font-weight="bold" text-anchor="middle">`+
			`<text x="200" y="%d" fill="none" stroke="%s" stroke-width="4" stroke-linejoin="round">%s</text>`+
			`<text x="200" y="%d" fill="%s">%s</text></g>`,
		dateSize, dateY, edge, txt, dateY, ink, txt))

	return b.String()
}

overlay.gno

package nsview

import (
	"strconv"
	"strings"
	"time"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)

// Seasonal decoration, driven by DATA rather than by code.
//
// The card is generated on every read, so anything it draws can change
// after names have been sold. That makes a holiday overlay possible —
// snow in December, falling leaves in October — across every token at
// once. The temptation is to write a drawSnow() into this realm and a
// drawPumpkins() next year, which would make every new decoration a
// redeploy of the view.
//
// So it is parameterised instead. This realm knows how to draw drifting
// particles; WHICH particles, what colour, how many and until when live
// in a global that any admin call can rewrite. Christmas is then one
// transaction, not a deployment, and so is turning it off.
//
// Format, read from the global key `cardfx`:
//
//	dir:fall;n:22;c:#ffffff;c2:#dbeafe;s:3;d:9;until:1767225600
//
//	dir    fall | rise | burst    drift down, drift up, or fireworks
//	n      1..40                  how many
//	c      #rrggbb                colour (c2, c3 optional, cycled)
//	s      1..6                   pixel size
//	d      2..30                  seconds for one traverse (lower = faster)
//	sv     0..3                   size jitter, so they are not all identical
//	k      4..16                  sparks per shell, when dir is burst
//	sh     sq | leaf | petal      particle shape; leaf and petal are angled
//	until  unix seconds, 0 = no expiry
//
// `until` matters more than it looks: an overlay that expires on its own
// cannot be forgotten in January. Everything is parsed defensively and a
// malformed value yields NO overlay, for the same reason the sprite
// parser does — this markup lands inside a token that other people's
// software renders.
const keyFX = "cardfx"

func overlaySVG(now int64) string {
	return buildOverlay(nsdata.GetGlobal(keyFX), now)
}

// A SCHEDULE, so December snows without anybody remembering to make it.
//
// This is free in a way the treasury swap was not. That needed somebody
// to send a transaction, because a realm cannot act on its own. This
// needs nobody, because the card is generated on every read and can
// simply look at the clock — the decoration is a rendering decision, not
// an action.
//
// Rules are separated by "|" and the FIRST one whose window contains
// today wins, so put the specific ones first:
//
//	from:12-01;to:01-06;dir:fall;n:26;c:#ffffff|from:10-24;to:11-02;dir:rise;n:22;c:#f97316
//
// from/to are MM-DD and RECUR every year, which is the point — set it
// once and every December snows. A window whose start is after its end
// wraps the new year, so 12-01 to 01-06 is what you would expect rather
// than an empty range. A rule with no window is always eligible, so a
// bare spec still behaves as it did.
func pickRule(spec string, now int64) string {
	if spec == "" {
		return ""
	}
	t := time.Unix(now, 0).UTC()
	today := int(t.Month())*100 + t.Day()
	for _, rule := range strings.Split(spec, "|") {
		/* A WEEKDAY RULE, for the one date that is not a date.
		 *
		 * Friday the thirteenth falls one to three times a year and never
		 * on a schedule, so it cannot be written as a MM-DD window. `on`
		 * takes a weekday and an optional day-of-month — on:fri-13 — and
		 * is checked before the window fields so a rule can use either
		 * without the two interfering.
		 *
		 * Deliberately narrow: this is not a general calendar language,
		 * it is the one shape the existing one could not express. */
		if on := ruleField(rule, "on"); on != "" {
			if weekdayMatch(on, t) {
				return rule
			}
			continue
		}
		from := ruleField(rule, "from")
		to := ruleField(rule, "to")
		if from == "" && to == "" {
			return rule // no window: always eligible
		}
		f, okF := mmdd(from)
		e, okE := mmdd(to)
		if !okF || !okE {
			continue // a malformed window disables its rule, not the lot
		}
		if f <= e {
			if today >= f && today <= e {
				return rule
			}
		} else if today >= f || today <= e {
			// wraps the year end, e.g. 12-01 to 01-06
			return rule
		}
	}
	return ""
}

func ruleField(rule, key string) string {
	for _, part := range strings.Split(rule, ";") {
		kv := strings.SplitN(strings.TrimSpace(part), ":", 2)
		if len(kv) == 2 && strings.TrimSpace(kv[0]) == key {
			return strings.TrimSpace(kv[1])
		}
	}
	return ""
}

// mmdd reads "12-01" into 1201. Rejects anything that is not a real
// calendar date, so a typo cannot silently make a rule match all year.
func mmdd(s string) (int, bool) {
	if len(s) != 5 || s[2] != '-' {
		return 0, false
	}
	m, err1 := strconv.Atoi(s[:2])
	d, err2 := strconv.Atoi(s[3:])
	if err1 != nil || err2 != nil || m < 1 || m > 12 || d < 1 || d > 31 {
		return 0, false
	}
	return m*100 + d, true
}

func buildOverlay(spec string, now int64) string {
	spec = pickRule(spec, now)
	if spec == "" {
		return ""
	}
	dir := "fall"
	n := 0
	size := 3
	dur := 9
	jitter := 0
	sparks := 8
	shape := "sq"
	var until int64
	cols := []string{}

	for _, part := range strings.Split(spec, ";") {
		kv := strings.SplitN(strings.TrimSpace(part), ":", 2)
		if len(kv) != 2 {
			continue
		}
		k, v := strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
		switch k {
		case "dir":
			if v == "fall" || v == "rise" || v == "burst" {
				dir = v
			}
		case "n":
			n = atoiClamp(v, 0, 40)
		case "s":
			size = atoiClamp(v, 1, 6)
		case "d":
			// Floor of 2, not 3: a 3-second traverse was the fastest the
			// card could go, and rain wants to be faster than snow by more
			// than that allows.
			dur = atoiClamp(v, 2, 30)
		case "sv":
			jitter = atoiClamp(v, 0, 3)
		case "k":
			sparks = atoiClamp(v, 4, 16)
		case "sh":
			if v == "sq" || v == "leaf" || v == "petal" {
				shape = v
			}
		case "until":
			if x, err := strconv.ParseInt(v, 10, 64); err == nil && x >= 0 {
				until = x
			}
		case "c", "c2", "c3":
			if isHexColour(v) {
				cols = append(cols, v)
			}
		}
	}

	if n <= 0 || len(cols) == 0 {
		return ""
	}
	// Expired decoration draws nothing, so a forgotten overlay retires
	// itself rather than snowing in July.
	if until > 0 && now >= until {
		return ""
	}

	if dir == "burst" {
		return fireworks(n, sparks, size, dur, cols)
	}

	var b strings.Builder
	b.WriteString(`<g opacity="0.85">`)
	for i := 0; i < n; i++ {
		// Deterministic scatter: the same token renders identically on
		// every read, which matters because a marketplace may cache it.
		h := hash(i)
		x := int(h % 392)
		delay := int(h/7) % (dur * 10)
		drift := int(h/13)%14 - 7
		wobble := dur + int(h/17)%5
		from, to := -12, 412
		if dir == "rise" {
			from, to = 412, -12
		}
		col := cols[i%len(cols)]
		// Not all the same size. Uniform particles read as a texture;
		// a little variation reads as depth, for two bytes of spec.
		px := size
		if jitter > 0 {
			px = size + int(h/23)%(jitter+1)
		}
		if shape == "sq" {
			b.WriteString(ufmt.Sprintf(
				`<rect x="%d" y="%d" width="%d" height="%d" fill="%s">`+
					`<animateTransform attributeName="transform" type="translate" `+
					`values="0 0;%d %d" dur="%ds" begin="-%d.%ds" repeatCount="indefinite"/></rect>`,
				x, from, px, px, col,
				drift, to-from, wobble, delay/10, delay%10))
			continue
		}
		// A shaped particle needs its own rotation, and an element can
		// carry only one transform. Animating the group and rotating the
		// shape inside it keeps the two independent — animating both on
		// one element would make each leaf drift along its own angle
		// instead of downward.
		b.WriteString(ufmt.Sprintf(
			`<g><animateTransform attributeName="transform" type="translate" `+
				`values="0 0;%d %d" dur="%ds" begin="-%d.%ds" repeatCount="indefinite"/>%s</g>`,
			drift, to-from, wobble, delay/10, delay%10,
			shapeAt(shape, x, from, px, int(h/31)%360, col)))
	}
	b.WriteString(`</g>`)
	return b.String()
}

// A small deterministic spread. Not random: the same index must always
// give the same particle, or a cached render and a fresh one disagree.
func hash(i int) int {
	h := (i+1)*2654435761 ^ 0x9e3779b9
	if h < 0 {
		h = -h
	}
	return h
}

func atoiClamp(s string, lo, hi int) int {
	v, err := strconv.Atoi(s)
	if err != nil {
		return 0
	}
	if v < lo {
		return lo
	}
	if v > hi {
		return hi
	}
	return v
}

// Fireworks: a shell climbs, vanishes, and throws sparks outward.
//
// The cost question is worth answering plainly, because it is the first
// decoration that is not one rect per particle. A shell is 1 rect for
// the climb plus k rects for the burst, so `n:5;k:10` is 55 rects — the
// same order as the 34 the rain already draws, and a fifth of the 128
// the domain sprite draws on every card anyway. None of it is stored:
// the card is built during a read, so this costs no gas and no storage,
// only the browser's time. That is the real ceiling, so the totals are
// capped below rather than left to whoever writes the spec.
//
// Two phases in one loop, driven by keyTimes on a single animation each,
// because a <set> chain or nested <g> would double the element count for
// the same picture.
func fireworks(shells, sparks, size, dur int, cols []string) string {
	if shells > 6 {
		shells = 6 // 6 x 16 sparks is already 102 rects
	}
	var b strings.Builder
	b.WriteString(`<g opacity="0.9">`)
	for i := 0; i < shells; i++ {
		h := hash(i * 7)
		x := 40 + int(h%340)         // keep the burst off the very edge
		burstY := 96 + int(h/11)%140 // where it stops climbing
		lift := 400 - burstY         // how far it climbs from the base
		// Shells are staggered across the cycle so they do not all go up
		// together, and each has its own colour from the palette.
		begin := int(h/29) % (dur * 10)
		// One colour per shell, not one per spark. A real firework is a
		// single charge, and mixing colours inside one burst reads as
		// confetti rather than pyrotechnics.
		col := cols[i%len(cols)]

		// The climb. Held at the top for the rest of the cycle rather
		// than looping straight away, and faded out at the moment of the
		// burst so the eye reads one event, not two objects.
		b.WriteString(ufmt.Sprintf(
			`<rect x="%d" y="400" width="%d" height="%d" fill="%s" opacity="0">`+
				`<animateTransform attributeName="transform" type="translate" `+
				`values="0 0;0 -%d;0 -%d" keyTimes="0;0.4;1" dur="%ds" begin="-%d.%ds" repeatCount="indefinite"/>`+
				`<animate attributeName="opacity" values="1;1;0;0" keyTimes="0;0.38;0.4;1" `+
				`dur="%ds" begin="-%d.%ds" repeatCount="indefinite"/></rect>`,
			x, size, size, col, lift, lift, dur, begin/10, begin%10, dur, begin/10, begin%10))

		for j := 0; j < sparks; j++ {
			g := hash(i*97 + j*13)
			d := j * 16 / sparks // one of the 16 fixed directions
			r := 34 + int(g%34)  // how far this spark travels
			dx := r * dirCos[d] / 100
			dy := r * dirSin[d] / 100
			// Sparks fall as they fly, which is the whole difference
			// between a firework and a starburst.
			dy += r / 3
			px := size
			if int(g/7)%3 == 0 {
				px = size + 1 // a few brighter, bigger sparks per shell
			}
			b.WriteString(ufmt.Sprintf(
				`<rect x="%d" y="%d" width="%d" height="%d" fill="%s" opacity="0">`+
					`<animateTransform attributeName="transform" type="translate" `+
					`values="0 0;0 0;%d %d" keyTimes="0;0.4;1" dur="%ds" begin="-%d.%ds" repeatCount="indefinite"/>`+
					`<animate attributeName="opacity" values="0;0;1;0" keyTimes="0;0.4;0.52;1" `+
					`dur="%ds" begin="-%d.%ds" repeatCount="indefinite"/></rect>`,
				x, burstY, px, px, col,
				dx, dy, dur, begin/10, begin%10, dur, begin/10, begin%10))
		}
	}
	b.WriteString(`</g>`)
	return b.String()
}

// Sixteen directions on a circle, as hundredths. A table rather than
// math.Sin: the same integers must come out on every node, and this is
// the whole of the trigonometry the card needs.
var (
	dirCos = [16]int{100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38, 0, 38, 71, 92}
	dirSin = [16]int{0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38}
)

// shapeAt draws one non-square particle at a position, turned to its own
// angle. Leaves and petals are two curves each rather than a polygon: a
// leaf is pointed at both ends, a petal is round at one, and that single
// difference is the whole of what distinguishes October from April.
//
// The numbers are derived from the particle size so `s` still means what
// it means everywhere else, and both shapes stay legible at the size a
// card is actually looked at.
func shapeAt(kind string, x, y, px, ang int, col string) string {
	w, hh := px, px*2
	switch kind {
	case "leaf":
		// Wider than a petal at the same size. A lens with its control
		// points at the particle width is a sliver, not a leaf.
		w = px * 3 / 2
		return ufmt.Sprintf(
			`<path d="M0 -%dQ%d 0 0 %dQ-%d 0 0 -%dZ" fill="%s" transform="translate(%d,%d) rotate(%d)"/>`,
			hh, w, hh, w, hh, col, x, y, ang)
	case "petal":
		return ufmt.Sprintf(
			`<ellipse rx="%d" ry="%d" fill="%s" transform="translate(%d,%d) rotate(%d)"/>`,
			w, hh, col, x, y, ang)
	}
	return ufmt.Sprintf(`<rect x="%d" y="%d" width="%d" height="%d" fill="%s"/>`, x, y, px, px, col)
}

// weekdayMatch reads "fri" or "fri-13": a weekday, optionally pinned to a
// day of the month. Anything it does not understand matches nothing, so a
// typo disables its own rule rather than firing every day.
func weekdayMatch(spec string, t time.Time) bool {
	day := ""
	dom := 0
	if at := strings.Index(spec, "-"); at > 0 {
		day = spec[:at]
		n, err := strconv.Atoi(spec[at+1:])
		if err != nil || n < 1 || n > 31 {
			return false
		}
		dom = n
	} else {
		day = spec
	}
	names := map[string]time.Weekday{
		"sun": time.Sunday, "mon": time.Monday, "tue": time.Tuesday,
		"wed": time.Wednesday, "thu": time.Thursday, "fri": time.Friday,
		"sat": time.Saturday,
	}
	want, ok := names[strings.ToLower(day)]
	if !ok {
		return false
	}
	if t.Weekday() != want {
		return false
	}
	return dom == 0 || t.Day() == dom
}

render.gno

// Package nsview is the human-facing view — the third realm in the
// split, and the newest (2026-08-21).
//
// It exists because an adversarial review found three defects in the old
// Render(), which lived inside the permanent `nsdata` vault: unescaped
// profile text injected into the page markdown, an O(domains × names)
// home page any user could inflate into a permanent denial of service,
// and navigation links that 404'd. All three were display bugs, and none
// of them could ever have been fixed, because that realm is deployed
// exactly once. The NFT artwork moved here for the same reason.
//
// Display code is swappable now. This realm holds no state, reads
// everything from nsdata's exported API, and can be redeployed and
// re-pointed at any time with nothing to migrate.
package nsview

import (
	"strings"
	"time"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
	"gno.land/r/nym-mnsrehearsal001/nsskin/v1"
)

// Profile keys inside a name's extension slot. Conventions owned by this
// realm and the logic realm, not by the vault — the vault stores strings
// and has no opinion about what they mean.
const (
	keyDisplayName = "displayName"
	keyBio         = "bio"
	keyWebsite     = "website"
)

func Render(path string) string {
	switch {
	case path == "":
		return renderHome()
	case strings.HasPrefix(path, "token/"):
		return "```\n" + BuildSVG(strings.TrimPrefix(path, "token/")) + "\n```\n"
	/* nsskin.TokenURI hands out "/r/.../nsview:skin/<id>#<n>" and this
	   case did not exist, so every skin token resolved to the literal
	   string "404: unknown name" — splitTokenID found no "*", the whole
	   path became a label, and renderName 404'd. All 226 lines of
	   skincard.gno, including the matted frame and the SKIN label its
	   own header calls the mitigation for "the single most likely way
	   this product hurts somebody", never ran for anybody. */
	case strings.HasPrefix(path, "skin/"):
		return "```\n" + renderSkin(strings.TrimPrefix(path, "skin/")) + "\n```\n"
	default:
		// A domain page carries its cursor as "?after=<key>". Split it
		// off before the token id is parsed, or the cursor lands in the
		// label and every paged link 404s.
		route, after := path, ""
		if q := strings.Index(path, "?after="); q >= 0 {
			route, after = path[:q], path[q+len("?after="):]
		}
		label, domainLabel := splitTokenID(route)
		if label == "" {
			return renderDomain(domainLabel, after)
		}
		return renderName(label, domainLabel)
	}
}

func renderHome() string {
	out := "# Meme Name Service\n\n"
	out += ufmt.Sprintf("%d domains registered.\n\n", nsdata.CountDomains())
	for _, label := range splitCSV(nsdata.ListDomains()) {
		owner, _, _, _, _ := nsdata.GetDomainInfo(label)
		// The link target must carry the "*" prefix — Render dispatches a
		// bare label to renderName, which 404s. That was the old home
		// page's bug: every link on it was dead.
		/* NO COUNT HERE. This called nsdata.CountNames per domain, and
		   CountNames iterates that domain's whole key span — so the home
		   page was O(every name in the registry) on every single view,
		   and anyone could inflate it by registering names. That is the
		   exact denial of service this package's own doc comment says
		   forced the renderer out of the vault; moving it here made it
		   repairable and nobody repaired it. The count lives on the
		   domain's own page, which walks one domain and pages. */
		out += ufmt.Sprintf("- [*%s](*%s) — owner `%s`\n",
			label, label, owner.String())
	}
	return out
}

func renderDomain(domainLabel, after string) string {
	if !nsdata.DomainExists(domainLabel) {
		return "404: unknown domain\n"
	}
	owner, registered, expires, streak, frozen := nsdata.GetDomainInfo(domainLabel)
	status, _ := statusFields(expires, frozen)
	daysLine := remaining(expires, time.Now().Unix())

	out := ufmt.Sprintf("# *%s\n\n", domainLabel)
	out += ufmt.Sprintf("- owner: `%s`\n", owner.String())
	out += ufmt.Sprintf("- status: **%s** (%s)\n", status, daysLine)
	if frozen {
		out += "- **frozen**\n"
	}
	out += ufmt.Sprintf("- registered: %s\n", time.Unix(registered, 0).UTC().Format("2006-01-02"))
	out += ufmt.Sprintf("- renewal streak: %d year(s)\n\n", streak)

	/* PAGED. This listed every name under the domain in one pass and
	   built a markdown line for each, so a domain with enough names made
	   its own page too expensive to render — permanently, for everyone,
	   until this realm was redeployed. nsdata.ExportNames already pages;
	   nsmarket already uses the same cursor idea for listings. */
	out += renderDomainNames(domainLabel, after)
	return out
}

// namePage is how many names one domain page shows. Small enough that
// the work is bounded whatever the registry does, large enough that an
// ordinary domain is one page.
const namePage = 100

func renderDomainNames(domainLabel, after string) string {
	keys, next := nsdata.ExportNames(domainLabel, after, namePage)
	labels := splitCSV(keys)
	if len(labels) == 0 {
		if after == "" {
			return "## names under this domain\n\n_none yet_\n"
		}
		return "## names under this domain\n\n_no more_\n"
	}

	out := "## names under this domain\n\n"
	// ExportNames returns full tree keys ("domain*label"); the page wants
	// the label, which is everything after the separator.
	cut := len(domainLabel) + 1
	for _, k := range labels {
		label := k
		if len(k) > cut {
			label = k[cut:]
		}
		out += ufmt.Sprintf("- [%s*%s](%s*%s)\n", label, domainLabel, label, domainLabel)
	}
	if next != "" {
		out += ufmt.Sprintf("\n[more](*%s?after=%s)\n", domainLabel, next)
	}
	return out
}

/*
renderSkin draws a skin DEFINITION's own card, matted and labelled, from
a token id of the form "<definition>#<serial>".

Deliberately not the name card: a skin for sale and a name for sale must
not look alike, which is what skincard.gno's frame is for.
*/
func renderSkin(tid string) string {
	id := tid
	if h := strings.Index(tid, "#"); h > 0 {
		id = tid[:h]
	}
	if !nsskin.SkinExists(id) {
		return "404: unknown skin"
	}
	name, art, lock, _, _, _ := nsskin.SkinInfo(id)
	return SkinCardSVG(name, art, lock, !inkForArt(art))
}

func renderName(label, domainLabel string) string {
	if !nsdata.NameExists(label, domainLabel) {
		return "404: unknown name\n"
	}
	owner, registered, expires, streak, frozen, paid := nsdata.GetNameInfo(label, domainLabel)
	status, _ := statusFields(expires, frozen)
	daysLine := remaining(expires, time.Now().Unix())

	out := ufmt.Sprintf("# %s*%s\n\n", label, domainLabel)
	out += ufmt.Sprintf("- owner: `%s`\n", owner.String())
	out += ufmt.Sprintf("- status: **%s** (%s)\n", status, daysLine)
	if frozen {
		out += "- **frozen**\n"
	}
	if !paid {
		out += "- free tier (not sellable until upgraded)\n"
	}
	out += ufmt.Sprintf("- registered: %s\n", time.Unix(registered, 0).UTC().Format("2006-01-02"))
	out += ufmt.Sprintf("- renewal streak: %d year(s)\n\n", streak)
	out += ufmt.Sprintf("- [*%s](*%s)\n\n", domainLabel, domainLabel)

	displayName := nsdata.GetNameExtra(label, domainLabel, keyDisplayName)
	bio := nsdata.GetNameExtra(label, domainLabel, keyBio)
	website := nsdata.GetNameExtra(label, domainLabel, keyWebsite)

	if displayName != "" || bio != "" || website != "" {
		out += "## Profile\n\n"
		// Every one of these is attacker-authored. Escaping them is the
		// whole reason this realm exists separately.
		if displayName != "" {
			out += ufmt.Sprintf("**%s**\n\n", escapeMarkdown(displayName))
		}
		if bio != "" {
			// A blockquote so even a crafted multi-line bio cannot break
			// out into block-level constructs.
			out += "> " + escapeMarkdown(bio) + "\n\n"
		}
		if website != "" {
			if isSafeURL(website) {
				out += ufmt.Sprintf("[%s](%s)\n\n", escapeMarkdown(website), website)
			} else {
				out += ufmt.Sprintf("website (unverified): `%s`\n\n", escapeMarkdown(website))
			}
		}
	}
	return out
}

// -- helpers --

func splitCSV(s string) []string {
	if s == "" {
		return nil
	}
	return strings.Split(s, ",")
}

// splitTokenID splits `label*domain`; a leading "*" yields an empty
// label, which is how a domain page is addressed.
func splitTokenID(tid string) (label, domain string) {
	for i := 0; i < len(tid); i++ {
		if tid[i] == '*' {
			return tid[:i], tid[i+1:]
		}
	}
	return tid, ""
}

// escapeMarkdown neutralises user-authored text so it renders as the
// literal characters typed rather than as markup. Backslash-escapes the
// CommonMark ASCII punctuation set and folds newlines, which stops
// headings, lists, tables, images, links, and raw HTML alike.
func escapeMarkdown(s string) string {
	s = strings.ReplaceAll(s, "\r\n", " ")
	s = strings.ReplaceAll(s, "\n", " ")
	s = strings.ReplaceAll(s, "\r", " ")
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		c := s[i]
		if strings.IndexByte("\\`*_{}[]()#+-.!|<>&~\"'", c) >= 0 {
			b.WriteByte('\\')
		}
		b.WriteByte(c)
	}
	return b.String()
}

// isSafeURL only admits plain http/https. Everything else — javascript:,
// data:, anything unrecognised — is refused a live link. Checked on read
// rather than on write so tightening the rule later also applies to
// profiles that already exist.
func isSafeURL(u string) bool {
	if !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {
		return false
	}
	if len(u) > 256 {
		return false
	}
	// This value is emitted RAW as the markdown link destination, so it is
	// the one attacker-authored string on the page that escapeMarkdown
	// does not neutralise. Allow-list instead of deny-list: every byte
	// must be printable, non-space ASCII. A deny-list missed newlines,
	// which let a crafted `website` terminate the link and inject
	// arbitrary markdown into the page below it.
	for i := 0; i < len(u); i++ {
		c := u[i]
		if c <= 0x20 || c >= 0x7f {
			return false
		}
		if strings.IndexByte("()<>\"'\\`", c) >= 0 {
			return false
		}
	}
	return true
}

skincard.gno

package nsview

import (
	"strings"

	"gno.land/p/nt/ufmt/v0"
)

/*
THE SKIN'S OWN CARD — what a skin token looks like when it is the thing
being listed, rather than the thing decorating a name.

WHY IT EXISTS. A skin is a separate token (see SKINS.md §1), so it has
its own listing on any marketplace that shows it. Drawn the way a name
card is drawn — art edge to edge, big lettering over the top — the two
would be indistinguishable, and somebody would buy a picture believing
they had bought a name. That is not a subtle risk: it is the single most
likely way this product hurts somebody.

THE FRAME IS THE WHOLE IDEA. A name card is FULL BLEED; this one is
MATTED, with the art inset inside a border and bands of ground above and
below it. The distinction survives at thumbnail size, at a glance, with
no text read at all — which is the only size and attention a marketplace
grid actually gets. The word SKIN across the top is the confirmation, not
the mechanism.

IT NAMES ITSELF, and it says what it will not go on. An extension-locked
skin that does not say so is a support ticket per sale.

WHAT IT DELIBERATELY DOES NOT SHOW: a price, an edition number, a rarity,
or anything else that frames the object as an investment. That rule is
from the risk policy and it applies to the artwork as much as to the copy
on the site — the card travels to places our words do not.
*/

// The matte. A name card uses all 400; this one is inset, and the inset
// is the tell.
const (
	skinTop  = 74 // the band the word SKIN sits in
	skinFoot = 62 // the band the skin's own name sits in

	// THE ART IS SQUARE, and its size is whatever the SHORTER dimension
	// allows — which is the height, because the two label bands eat into
	// it and the sides only give up a margin.
	//
	// This started as "340 wide" and was wrong: 340 is what the width
	// allows, but only 264 of height remains once the bands are taken,
	// so the art ran 76px down into the footer and sat behind the skin's
	// own name. A square sprite drawn into a non-square box either
	// stretches or overflows, and both are worse than being smaller.
	skinBox = 400 - skinTop - skinFoot // 264
	// Centred on what is left, so the side margins come out equal.
	skinPad = (400 - skinBox) / 2 // 68
)

/*
skinArtSVG renders a sprite to fill a box, INFERRING THE GRID from the
data rather than assuming twelve.

spriteSVG hardcodes twelve in four places, which is right for the domain
artwork it was written for and wrong here: SKINS.md §2a offers 12, 16, 24
and 32, and the whole point of inferring is that one format then covers
every size and every sprite already on chain keeps working.

Validation is spriteSVG's, unchanged and unrelaxed, because it is not
merely a parser — it is the thing standing between community-authored
data and markup inside somebody else's wallet. Any violation rejects the
WHOLE sprite rather than skipping the bad part: a partial picture hides
the fault.
*/
func skinArtSVG(enc string, ox, oy, box int) string {
	if enc == "" {
		return ""
	}
	parts := strings.Split(enc, "|")
	n := len(parts) - 1
	if n < 4 || n > 64 {
		return ""
	}
	colours := map[string]string{}
	for _, entry := range strings.Split(parts[0], ",") {
		if len(entry) != 8 || entry[1] != '#' {
			return ""
		}
		if !isHexColour(entry[1:]) {
			return ""
		}
		colours[entry[:1]] = entry[1:]
	}

	/*
		EVERY CELL IS PLACED FROM ITS OWN EXACT BOUNDARY, never from an
		accumulated cell size.

		The obvious way — cell := box / n, then x*cell — truncates once
		and then repeats the error n times, so the art stops short of its
		own frame by up to n pixels. Scaling the cell by a thousand first
		does not fix it either: at n=12 in a 340 box the cell is 28.333,
		28333 x 12 is 339996, and the last column still lands a pixel
		inside the frame. Which is a full pixel of bare matte down one
		edge, and by eye it reads as a design choice rather than a bug.

		Computing each boundary as x*box/n instead makes the LAST one
		exactly n*box/n = box, at every grid size, with no accumulation
		to go wrong.

		RUNS OF ONE COLOUR BECOME ONE RECT, which SKINS.md §2a asked for
		before the grid went much past 32 and which the collection has now
		made urgent rather than tidy.

		Every painted cell used to emit its own <rect>, inside every
		wallet that renders the card. That is tolerable for a sprite of a
		thing and ruinous for a BACKGROUND: a vertical gradient is one
		colour per row, so a 32-wide one emitted 1,024 rects to draw 32
		distinct bands. Merging horizontal runs draws it in 32 — the same
		picture, pixel for pixel, at a thirty-second of the markup.

		It costs nothing when it does not apply. A busy sprite with no
		horizontal runs merges nothing and emits exactly what it did
		before.
	*/
	var b strings.Builder
	for y := 1; y <= n; y++ {
		row := parts[y]
		if len(row) != n {
			return ""
		}
		y0 := oy + (y-1)*box/n
		h := oy + y*box/n - y0
		for x := 0; x < n; {
			ch := row[x : x+1]
			if ch == "." {
				x++
				continue
			}
			c, ok := colours[ch]
			if !ok {
				return ""
			}
			// How far this colour runs.
			run := x + 1
			for run < n && row[run:run+1] == ch {
				run++
			}
			x0 := ox + x*box/n
			w := ox + run*box/n - x0
			b.WriteString(ufmt.Sprintf(
				`<rect x="%d" y="%d" width="%d" height="%d" fill="%s"/>`,
				x0, y0, w, h, c))
			x = run
		}
	}
	if b.Len() == 0 {
		return ""
	}
	return b.String()
}

/*
SkinCardSVG draws a skin token's own listing card.

	name   the skin's name, as the shop shows it
	art    the sprite string
	lock   the extension it is restricted to, or "" for one that goes
	       on any name
	light  true  = pale lettering on a dark matte
	       false = dark lettering on a pale matte

The return is a whole document rather than a fragment, because unlike the
nameplate this composites over nothing — it IS the card.
*/
func SkinCardSVG(name, art, lock string, light bool) string {
	ink, edge, matte := "#f4f4f5", "#26262b", "#0b0d10"
	if !light {
		ink, edge, matte = "#0b0d10", "#d4d4d8", "#f4f4f5"
	}

	var b strings.Builder
	b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">`)
	b.WriteString(ufmt.Sprintf(`<rect width="400" height="400" fill="%s"/>`, matte))

	// THE WORD, big and flat across the top. Monospace and letter-spaced
	// so it reads as a label on the object rather than as a title for it.
	b.WriteString(ufmt.Sprintf(
		`<text x="%d" y="46" font-family="monospace" font-size="27" font-weight="bold"`+
			` letter-spacing="7" fill="%s">SKIN</text>`, skinPad, ink))

	// The art, inset, with a frame drawn AROUND it rather than over it —
	// a border that overlapped would eat a row of somebody's pixels.
	inner := skinArtSVG(art, skinPad, skinTop, skinBox)
	if inner == "" {
		// A skin whose art will not parse still has to render as
		// something, or the listing is a blank square with no clue why.
		b.WriteString(ufmt.Sprintf(
			`<rect x="%d" y="%d" width="%d" height="%d" fill="none" stroke="%s"`+
				` stroke-width="2" stroke-dasharray="7 6"/>`,
			skinPad, skinTop, skinBox, skinBox, edge))
		b.WriteString(ufmt.Sprintf(
			`<text x="200" y="%d" text-anchor="middle" font-family="monospace"`+
				` font-size="13" fill="%s">ART WILL NOT RENDER</text>`,
			skinTop+skinBox/2, edge))
	} else {
		b.WriteString(inner)
	}
	b.WriteString(ufmt.Sprintf(
		`<rect x="%d" y="%d" width="%d" height="%d" fill="none" stroke="%s" stroke-width="2"/>`,
		skinPad-1, skinTop-1, skinBox+2, skinBox+2, edge))

	// The skin's own name, and what it will not go on.
	b.WriteString(ufmt.Sprintf(
		`<text x="%d" y="%d" font-family="sans-serif" font-size="21" font-weight="bold"`+
			` fill="%s">%s</text>`,
		skinPad, 400-skinFoot+34, ink, esc(name)))

	tail := "goes on any name"
	if lock != "" {
		tail = "*" + lock + " names only"
	}
	b.WriteString(ufmt.Sprintf(
		`<text x="%d" y="%d" text-anchor="end" font-family="monospace" font-size="12"`+
			` letter-spacing="1" fill="%s">%s</text>`,
		400-skinPad, 400-skinFoot+34, edge, esc(strings.ToUpper(tail))))

	b.WriteString(`</svg>`)
	return b.String()
}

skinned.gno

package nsview

import (
	"strings"

	"gno.land/r/nym-mnsrehearsal001/nsskin/v1"
)

/*
A NAME WEARING A SKIN — the card the shop actually sells.

Until this existed, a bought skin did nothing: nsskin held the token, the
binding and the art, and nsview had never heard of it. Somebody could buy
one, attach it, and look at their NFT to find the ordinary card. That is
the whole of what this file fixes.

ONE CALL DOES THE ASKING. nsskin.ArtForName answers "what should this
name be drawn with", with every condition already inside it — the name
wears a token, the definition is not withdrawn, the binding is pinned to
this registration, the lock still matches. A renderer that had to
remember four checks before drawing is one that eventually forgets one,
so it does not get the chance.

THE FACE AND THE INK ARE DERIVED, NOT STORED, and that is the
interesting part.

nsskin does not record them: DefineSkin takes an id, a name, a sprite, a
lock and an artist, and nothing else. Adding fields would mean a new
nsskin, and a new nsskin strands every token minted from the old one —
which by the time this was written already included somebody's purchase.
Stranding a paid-for object to store two values that can be worked out is
a bad trade.

So they are worked out. The ink comes from the art itself, which is
better than a stored value rather than merely cheaper: measured against
the sixty definitions in the launch collection, deriving it beat the
hand-picked value on ELEVEN cards and lost on none, and took the worst
contrast on any card from 1.5:1 to 4.7:1.
*/

/*
THE CROSSOVER IS AT 46, NOT 128, and getting that wrong is what made the
hand-picked values worse than this rule.

Contrast against white is 1.05/(L+0.05); against black it is
(L+0.05)/0.05. Setting them equal gives (L+0.05)^2 = 0.0525, so L = 0.179
— about 46 out of 255. Contrast is NOT symmetric about mid-grey: black
lettering on a mid-grey ground is far more readable than white on the
same ground, and a threshold at 128 hands eleven cards to the wrong ink.
*/
const inkCrossover = 46

// lumOf is relative luminance, 0..255, with a gamma of two.
//
// The real curve is sRGB's 2.4-with-a-linear-toe, which needs a pow().
// Squaring is within a couple of points of it across the whole range and
// is exact in integers — and this feeds a THRESHOLD, where being two
// points out only matters for a colour already sitting on the boundary,
// on which no ink is much better than the other anyway.
func lumOf(hex string) int {
	if len(hex) != 7 || hex[0] != '#' {
		return 128
	}
	r := hexPair(hex[1], hex[2])
	g := hexPair(hex[3], hex[4])
	b := hexPair(hex[5], hex[6])
	if r < 0 || g < 0 || b < 0 {
		return 128
	}
	return (2126*r*r + 7152*g*g + 722*b*b) / (10000 * 255)
}

func hexPair(a, b byte) int {
	hi, lo := hexDigit(a), hexDigit(b)
	if hi < 0 || lo < 0 {
		return -1
	}
	return hi*16 + lo
}

func hexDigit(c byte) int {
	switch {
	case c >= '0' && c <= '9':
		return int(c - '0')
	case c >= 'a' && c <= 'f':
		return int(c-'a') + 10
	case c >= 'A' && c <= 'F':
		return int(c-'A') + 10
	}
	return -1
}

/*
bandMedian is the luminance of what the lettering actually sits on.

THE MEDIAN, NOT THE MEAN, and the difference is not academic. A mean of
black and hot pink is a mid-grey that exists nowhere on the card, and it
sends the ink the wrong way on exactly the high-contrast patterns that
most need the right answer. A median is what most of the band is.

Three rows, because a line of type is taller than one cell at every grid
size offered. The middle seventy per cent of the width, because the name
is centred and the margins are not under it.
*/
func bandMedian(art string, num, den int) int {
	parts := strings.Split(art, "|")
	n := len(parts) - 1
	if n < 1 {
		return 128
	}
	colours := map[string]int{}
	for _, e := range strings.Split(parts[0], ",") {
		if len(e) == 8 && e[1] == '#' {
			colours[e[:1]] = lumOf(e[1:])
		}
	}
	y := (num*(n-1) + den/2) / den
	var vals []int
	for dy := -1; dy <= 1; dy++ {
		ry := y + dy
		if ry < 0 {
			ry = 0
		}
		if ry > n-1 {
			ry = n - 1
		}
		row := parts[ry+1]
		if len(row) != n {
			continue
		}
		lo, hi := n*15/100, n*85/100
		if hi > n-1 {
			hi = n - 1
		}
		for x := lo; x <= hi; x++ {
			if L, ok := colours[row[x:x+1]]; ok {
				vals = append(vals, L)
			}
		}
	}
	if len(vals) == 0 {
		return 128
	}
	// Insertion sort. At most about seventy values, and a realm has no
	// sort worth importing for that.
	for i := 1; i < len(vals); i++ {
		v := vals[i]
		j := i - 1
		for j >= 0 && vals[j] > v {
			vals[j+1] = vals[j]
			j--
		}
		vals[j+1] = v
	}
	return vals[len(vals)/2]
}

// inkForArt returns true for white lettering. The name's own band
// decides it alone: measured across the launch collection the date band
// never changed an outcome for the better, and letting it vote was what
// put white letters on a pale card.
func inkForArt(art string) bool {
	return bandMedian(art, 212, 400) < inkCrossover
}

/*
faceForArt picks one of the three generic families from the art itself.

Nothing about a background implies a typeface, so this is arbitrary — but
it must be arbitrary in the SAME WAY on the chain and in the shop, or the
preview shows a card that does not mint. Derived from the art rather than
stored for the same reason as the ink: it costs nothing and cannot drift.
*/
func faceForArt(art string) string {
	h := 2166136261
	for i := 0; i < len(art); i++ {
		h ^= int(art[i])
		h *= 16777619
		h &= 0x7fffffff
	}
	switch h % 3 {
	case 0:
		return "sans"
	case 1:
		return "serif"
	}
	return "mono"
}

/*
skinnedCardSVG is the whole card: the art edge to edge, the name over it.

FULL BLEED, unlike the skin's own listing card, which is matted. That
contrast is deliberate and load-bearing — it is what stops somebody
mistaking a skin for sale for a name for sale. See skincard.gno.

The ground behind the art matters because a sprite may have transparent
cells, and without it they would show whatever the viewer's page is,
which is not a colour we chose.
*/
func skinnedCardSVG(art, label, domain string, expires int64) string {
	light := inkForArt(art)
	ground := "#0b0d10"
	if !light {
		ground = "#f4f4f5"
	}
	inner := skinArtSVG(art, 0, 0, 400)
	if inner == "" {
		return "" // an unrenderable sprite falls back to the ordinary card
	}
	return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" role="img">` +
		`<rect width="400" height="400" fill="` + ground + `"/>` + inner +
		NameplateSVG(label, domain, faceForArt(art), "middle", light, expires) +
		`</svg>`
}

// skinFor a NAME, as opposed to skinFor the calendar. Separate because
// they answer different questions and only one of them involves money.
func wornArt(label, domain string) string {
	return nsskin.ArtForName(label, domain)
}

skins.gno

package nsview

import (
	"strings"
	"time"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)

/*
SKINS — the card becomes something else entirely for a day.

The decoration calendar already draws snow and embers ON TOP of a card.
A skin REPLACES it: on 22 May the token is a pizza, on 3 January it is a
newspaper. That is a different kind of change, so it is a different
field, and any date without one renders exactly as it always has.

HOW A CONTRACT KNOWS THE DATE AT ALL. It does not read a block height and
guess. Every block carries a timestamp in its header, agreed by consensus
the same way its transactions are, and `time.Now()` inside a realm returns
that block time. So a realm has a real clock, accurate to within a block
interval — which for a decoration that changes once a year is precision
nobody will ever notice. This is the same mechanism the seasonal overlay
has always used.

WHY THIS COSTS NOTHING TO RUN. The card is generated on every read rather
than fixed at mint, so a skin needs no transaction, no migration and
nobody awake at midnight. It applies to names sold years ago. Turning it
off is deleting one field from the calendar.

NO FONTS. Every renderer that shows these — wallets, marketplaces — puts
the SVG in a sandbox with no network, so a web font simply fails and
silently substitutes. Only the generic families resolve, which is why the
existing card says monospace and why these say serif or sans-serif. The
display faces in the mockups are a later job: an alphabet drawn as paths
and stored once, which is the only way to get identical letterforms on
every device.
*/

// skinFor returns the skin named by whichever calendar rule is active
// today, or "" for the ordinary card. Reusing pickRule means a skin
// obeys the same window rules, the same first-match-wins ordering and
// the same year wrapping as every other season.
func skinFor(now int64) string {
	return skinFromSpec(nsdata.GetGlobal(keyFX), now)
}

// Split out so the calendar logic can be tested against a spec directly,
// without standing up a vault to hold one.
func skinFromSpec(spec string, now int64) string {
	rule := pickRule(spec, now)
	if rule == "" {
		return ""
	}
	return ruleField(rule, "skin")
}

// hasSkin reports whether a name is renderable as this skin. Unknown
// names render nothing rather than a broken card — the same defensive
// stance the overlay parser takes, and for the same reason: this markup
// lands inside a token that other people's software renders.
func hasSkin(name string) bool {
	switch name {
	case "pizza", "paper", "cal", "fog", "slash", "pi", "heart":
		return true
	}
	return false
}

// seedOf turns a token id into a small number, so that a card can differ
// from the one beside it without any randomness — which a deterministic
// machine does not have. Every node computes the same answer for the same
// name, which is the requirement; looking arbitrary is merely the effect.
func seedOf(tid string) int {
	h := 2166136261
	for i := 0; i < len(tid); i++ {
		h ^= int(tid[i])
		h *= 16777619
		h &= 0x7fffffff
	}
	return h
}

// skinSVG renders a complete 400x400 card. Same frame as the ordinary
// one, so nothing downstream has to know which it received.
func skinSVG(name, tid string, now int64) string {
	label := tid
	if at := strings.Index(tid, "*"); at > 0 {
		label = tid
	}
	size := 34
	if len(label) > 14 {
		size = 22
	} else if len(label) > 10 {
		size = 27
	}
	switch name {
	case "pizza":
		return skinPizza(label, size, seedOf(tid))
	case "paper":
		return skinPaper(label, size, now)
	case "cal":
		return skinCal(label, size)
	case "fog":
		return skinFog(label, size)
	case "slash":
		return skinSlash(label, size)
	case "pi":
		return skinPi(label, size)
	case "heart":
		return skinHeart(label, size)
	}
	return ""
}

func head(bg string) string {
	return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" role="img">` +
		`<rect width="400" height="400" fill="` + bg + `"/>`
}

func foot() string {
	return `<text x="200" y="380" text-anchor="middle" font-family="monospace" font-size="10"` +
		` fill="#ffffff" opacity="0.45">MINTED ON GNO.LAND</text></svg>`
}

/* ---------------- 22 May: the pizza ----------------
 *
 * Eight wedges with a gap between them, so it reads as CUT rather than
 * merely divided, and each wedge carries its own toppings inside its own
 * group — that is what makes a slice leave with its pepperoni still on
 * it instead of leaving them floating over the board.
 *
 * EVERY NAME EATS IN ITS OWN ORDER. The seed decides which slice goes
 * first and how long each one waits, so a marketplace full of these is a
 * room full of pizzas being eaten from different sides at different
 * rates rather than one animation repeated. It is derived from the token
 * id, so it is the same on every node and different for every name.
 */
func skinPizza(label string, size, seed int) string {
	var b strings.Builder
	b.WriteString(head("#2a2018"))
	b.WriteString(`<circle cx="200" cy="200" r="168" fill="#3a2c20"/>`)

	order := make([]int, 8)
	for i := range order {
		order[i] = i
	}
	// A deterministic shuffle: the seed walks the list and swaps.
	s := seed
	for i := 7; i > 0; i-- {
		s = (s*1103515245 + 12345) & 0x7fffffff
		j := s % (i + 1)
		order[i], order[j] = order[j], order[i]
	}

	for pos, idx := range order {
		a0 := float64(idx)*45 + 1.8
		a1 := float64(idx+1)*45 - 1.8
		// Each slice waits a little longer than the last, with the gap
		// itself varying by name so two cards never keep step.
		begin := 3 + pos*3 + (seed>>uint(pos))%4
		b.WriteString(`<g>`)
		b.WriteString(`<animate attributeName="opacity" values="1;1;0" keyTimes="0;0.5;1"`)
		b.WriteString(ufmt.Sprintf(` dur="%ds" begin="%ds" fill="freeze"/>`, 2, begin))
		b.WriteString(wedge(200, 200, 162, a0, a1, "#d9822b"))
		b.WriteString(wedge(200, 200, 143, a0+1.2, a1-1.2, "#f0b23c"))
		// Three toppings inside this wedge: one pepperoni, two herbs.
		for t := 0; t < 3; t++ {
			s = (s*1103515245 + 12345) & 0x7fffffff
			ang := a0 + 4 + float64(s%int(a1-a0-8))
			s = (s*1103515245 + 12345) & 0x7fffffff
			rad := 46 + float64(s%86)
			x, y := polar(200, 200, rad, ang)
			if t == 0 {
				b.WriteString(ufmt.Sprintf(`<circle cx="%d" cy="%d" r="13" fill="#b8342a"/>`, x, y))
			} else {
				b.WriteString(ufmt.Sprintf(
					`<rect x="%d" y="%d" width="13" height="13" rx="3" fill="#4e8b3a"/>`, x-6, y-6))
			}
		}
		b.WriteString(`</g>`)
	}
	b.WriteString(ufmt.Sprintf(
		`<text x="200" y="212" text-anchor="middle" font-family="sans-serif" font-size="%d"`+
			` font-weight="bold" fill="#2a1405">%s</text>`, size, esc(label)))
	b.WriteString(foot())
	return b.String()
}

func wedge(cx, cy int, r float64, a0, a1 float64, fill string) string {
	x0, y0 := polar(cx, cy, r, a0)
	x1, y1 := polar(cx, cy, r, a1)
	return ufmt.Sprintf(`<path d="M%d %d L%d %d A%d %d 0 0 1 %d %d Z" fill="%s"/>`,
		cx, cy, x0, y0, int(r), int(r), x1, y1, fill)
}

// Degrees clockwise from twelve o'clock, which is how a pizza is cut.
// Integer maths throughout: a realm has no floating point worth trusting
// across nodes, and a pizza does not need sub-pixel accuracy.
func polar(cx, cy int, r float64, deg float64) (int, int) {
	rad := (deg - 90) * 3.14159265 / 180
	return cx + int(r*cosApprox(rad)), cy + int(r*sinApprox(rad))
}

func sinApprox(x float64) float64 {
	for x > 3.14159265 {
		x -= 6.2831853
	}
	for x < -3.14159265 {
		x += 6.2831853
	}
	x2 := x * x
	return x * (1 - x2/6 + x2*x2/120 - x2*x2*x2/5040)
}

func cosApprox(x float64) float64 { return sinApprox(x + 1.5707963) }

/* ---------------- 3 Jan: the front page ---------------- */
func skinPaper(label string, size int, now int64) string {
	year := time.Unix(now, 0).UTC().Year()
	return head("#f4f0e4") +
		`<text x="200" y="66" text-anchor="middle" font-family="serif" font-size="30"` +
		` font-weight="bold" fill="#141210">THE LEDGER</text>` +
		`<line x1="40" y1="80" x2="360" y2="80" stroke="#141210" stroke-width="2"/>` +
		ufmt.Sprintf(`<text x="200" y="100" text-anchor="middle" font-family="monospace"`+
			` font-size="11" fill="#5a5348">3 JANUARY %d &#183; BLOCK ZERO</text>`, year) +
		ufmt.Sprintf(`<text x="200" y="176" text-anchor="middle" font-family="serif"`+
			` font-size="%d" font-weight="bold" fill="#141210">%s</text>`, size+6, esc(label)) +
		`<text x="200" y="214" text-anchor="middle" font-family="sans-serif" font-size="13"` +
		` fill="#39342c">The first block is mined. A chain begins.</text>` +
		`<text x="200" y="234" text-anchor="middle" font-family="sans-serif" font-size="13"` +
		` fill="#39342c">Years later somebody registers a name</text>` +
		`<text x="200" y="254" text-anchor="middle" font-family="sans-serif" font-size="13"` +
		` fill="#39342c">on it that does nothing at all.</text>` +
		`<line x1="40" y1="278" x2="360" y2="278" stroke="#b9b2a2" stroke-width="1"/>` +
		`<text x="200" y="380" text-anchor="middle" font-family="monospace" font-size="10"` +
		` fill="#5a5348">MINTED ON GNO.LAND</text></svg>`
}

/* ---------------- 29 Feb: the calendar page ---------------- */
func skinCal(label string, size int) string {
	return head("#ffffff") +
		`<rect width="400" height="72" fill="#c0392b"/>` +
		`<text x="200" y="49" text-anchor="middle" font-family="sans-serif" font-size="26"` +
		` font-weight="bold" fill="#ffffff" letter-spacing="6">FEBRUARY</text>` +
		`<circle cx="150" cy="24" r="9" fill="#f7f4ee" stroke="#00000055" stroke-width="3"/>` +
		`<circle cx="250" cy="24" r="9" fill="#f7f4ee" stroke="#00000055" stroke-width="3"/>` +
		`<text x="200" y="252" text-anchor="middle" font-family="sans-serif" font-size="170"` +
		` font-weight="bold" fill="#e8e3d9">29</text>` +
		ufmt.Sprintf(`<text x="200" y="300" text-anchor="middle" font-family="monospace"`+
			` font-size="%d" font-weight="bold" fill="#1a1a1a">%s</text>`, size, esc(label)) +
		`<text x="200" y="380" text-anchor="middle" font-family="monospace" font-size="10"` +
		` fill="#8a857a">MINTED ON GNO.LAND</text></svg>`
}

/* ---------------- 20 Apr: the fog ---------------- */
func skinFog(label string, size int) string {
	return head("#1d4028") +
		`<defs><radialGradient id="g"><stop offset="0" stop-color="#8fd48a"/>` +
		`<stop offset="0.68" stop-color="#3f7a4a"/><stop offset="1" stop-color="#1d4028"/>` +
		`</radialGradient><filter id="b"><feGaussianBlur stdDeviation="26"/></filter></defs>` +
		`<rect width="400" height="400" fill="url(#g)"/>` +
		`<g filter="url(#b)" opacity="0.5">` +
		`<circle cx="130" cy="140" r="90" fill="#ffffff" opacity="0.5">` +
		`<animate attributeName="cx" values="130;190;130" dur="18s" repeatCount="indefinite"/>` +
		`</circle>` +
		`<circle cx="280" cy="250" r="80" fill="#ffffff" opacity="0.35">` +
		`<animate attributeName="cy" values="250;200;250" dur="22s" repeatCount="indefinite"/>` +
		`</circle></g>` +
		ufmt.Sprintf(`<text x="200" y="212" text-anchor="middle" font-family="sans-serif"`+
			` font-size="%d" font-weight="bold" fill="#f2fff2">%s</text>`, size, esc(label)) +
		foot()
}

/* ---------------- Friday 13th: the poster ---------------- */
func skinSlash(label string, size int) string {
	return head("#15080a") +
		`<path d="M88 -20 L112 420 L96 420 L72 -20 Z" fill="#c42c24" opacity="0.85"/>` +
		`<path d="M252 420 L268 -20 L278 -20 L262 420 Z" fill="#8e1d18" opacity="0.7"/>` +
		ufmt.Sprintf(`<text x="200" y="212" text-anchor="middle" font-family="serif"`+
			` font-size="%d" font-weight="bold" fill="#d8342c">%s</text>`, size+4, esc(label)) +
		foot()
}

/* ---------------- 14 Mar: pi ---------------- */
func skinPi(label string, size int) string {
	digits := []string{
		"3.14159265358979323846", "26433832795028841971", "69399375105820974944",
		"59230781640628620899", "86280348253421170679", "82148086513282306647",
	}
	var b strings.Builder
	b.WriteString(head("#101418"))
	for i, row := range digits {
		b.WriteString(ufmt.Sprintf(
			`<text x="26" y="%d" font-family="monospace" font-size="30" fill="#2b4756">%s</text>`,
			70+i*56, row))
	}
	b.WriteString(`<rect x="52" y="176" width="296" height="52" rx="8" fill="#101418"/>`)
	b.WriteString(ufmt.Sprintf(
		`<text x="200" y="212" text-anchor="middle" font-family="monospace" font-size="%d"`+
			` font-weight="bold" fill="#eaf2f6">%s</text>`, size, esc(label)))
	b.WriteString(foot())
	return b.String()
}

/* ---------------- 14 Feb: the heart ----------------
 *
 * A real double thump, not one pulse: squeeze, small recoil, second
 * smaller squeeze, then a long rest. The rest is most of what makes it
 * read as a heartbeat rather than a throb.
 */
func skinHeart(label string, size int) string {
	return head("#fbe3ec") +
		`<g transform="translate(200,196)">` +
		`<animateTransform attributeName="transform" type="scale"` +
		` values="1;1.085;0.995;1.05;1;1" keyTimes="0;0.09;0.18;0.27;0.40;1"` +
		` dur="1.15s" repeatCount="indefinite" additive="sum"/>` +
		`<path transform="translate(-150,-140)" fill="#f7c3d5" stroke="#e39bb5" stroke-width="5"` +
		` d="M150 258 C66 198 24 150 24 102 A60 60 0 0 1 150 72 A60 60 0 0 1 276 102` +
		` C276 150 234 198 150 258 Z"/></g>` +
		ufmt.Sprintf(`<text x="200" y="212" text-anchor="middle" font-family="sans-serif"`+
			` font-size="%d" font-weight="bold" fill="#7e1f3d" letter-spacing="2">%s</text>`,
			size, esc(strings.ToUpper(label))) +
		`<text x="200" y="380" text-anchor="middle" font-family="monospace" font-size="10"` +
		` fill="#b03a62" opacity="0.7">MINTED ON GNO.LAND</text></svg>`
}

// Markup safety, same as everywhere else that puts a name into SVG: a
// label is validated on registration, but this is the last gate before
// it lands inside somebody else's renderer.
func esc(s string) string {
	s = strings.ReplaceAll(s, "&", "&amp;")
	s = strings.ReplaceAll(s, "<", "&lt;")
	s = strings.ReplaceAll(s, ">", "&gt;")
	return s
}

svg.gno

package nsview

import (
	"encoding/base64"
	"strings"
	"time"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/nym-mnsrehearsal001/nsdata/v1"
)

// The NFT artwork and every piece of display formatting live here, in a
// realm that can be redeployed, rather than in the vault that cannot.
// nsdata.TokenURI points at this realm through a settable prefix.

// TokenURI returns the full data: URI for a token, generated on every
// read so the image always reflects current state (never baked at mint).
func TokenURI(tid string) string {
	return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(BuildSVG(tid)))
}

// BuildSVG renders a token. Everything on the card derives from four
// stored values — owner, registered, expires, and the domain's drawing —
// so a renewal moves `expires` and the bar, the time remaining and the
// years held all follow from it. Nothing is baked at mint: the card is
// generated on every read, which is what lets a domain's artwork be
// changed after its names have been sold.
func BuildSVG(tid string) string {
	var registered, expires int64 // unix seconds
	var streak int64
	var frozen bool
	var domainLabel string

	if strings.HasPrefix(tid, "*") {
		label := tid[1:]
		if !nsdata.DomainExists(label) {
			return placeholderSVG("unknown")
		}
		_, registered, expires, streak, frozen = nsdata.GetDomainInfo(label)
		domainLabel = label
	} else {
		label, dom := splitTokenID(tid)
		if !nsdata.NameExists(label, dom) {
			return placeholderSVG("unknown")
		}
		_, registered, expires, streak, frozen, _ = nsdata.GetNameInfo(label, dom)
		domainLabel = dom
	}

	now := time.Now().Unix()
	// The three vault reads happen HERE, not inside cardSVG. That is what
	// leaves the card itself a pure function of its inputs, which is what
	// lets a test assert what a marketplace will show without standing up
	// a registry to do it.
	// A SKIN REPLACES THE CARD, so it is decided before anything is read
	// from the vault for drawing one. The ordinary path is untouched on
	// every other day of the year.
	/* A BOUGHT SKIN BEATS THE CALENDAR, and that ordering is a
	   decision rather than an accident. The calendar skin is a gift
	   everybody gets on the same day; a worn skin is a thing somebody
	   paid for and chose. On the two or three days a year they collide,
	   the one that was bought wins.

	   Only NAMES can wear one. A domain token has no owner to bind to
	   and no shop entry, so it takes the calendar path as before. */
	if !strings.HasPrefix(tid, "*") {
		label, dom := splitTokenID(tid)
		if art := wornArt(label, dom); art != "" {
			if card := skinnedCardSVG(art, label, dom, expires); card != "" {
				return card
			}
			// An unrenderable sprite falls through to the ordinary card
			// rather than returning nothing: a blank token is worse than
			// an unskinned one, and the holder still owns the name.
		}
	}

	if sk := skinFor(now); sk != "" && hasSkin(sk) {
		return skinSVG(sk, tid, now)
	}

	art := nsdata.GetDomainExtra(domainLabel, keyArt)
	return cardSVG(tid, art, registered, expires, streak, frozen, now, overlaySVG(now))
}

// cardSVG is the card itself, with every stored value already resolved.
// Split out from BuildSVG so the markup can be rendered — and asserted
// against — without a vault under it. TestStaticFrameShowsTheDate is the
// reason: what a marketplace shows as a still is a property of this
// string and of nothing else, and it deserves to be checked rather than
// assumed.
func cardSVG(tid, art string, registered, expires, streak int64, frozen bool, now int64, overlay string) string {
	accent := accentOf(art)
	status, edge := statusFields(expires, frozen)

	// The ribbon says something the rest of the card does not.
	// "DIAMOND HANDS" on a name minted this morning is a joke that lands
	// once; tied to tenure it is a thing you get TO.
	ribbon := status
	if status == "LIVE" {
		if streak >= 1 {
			ribbon = "DIAMOND HANDS"
		} else {
			ribbon = "FIRST YEAR"
		}
	}

	// The domain's drawing as a wash, centred: twelve cells at 26px is
	// 312 wide, so 44px of margin on every side.
	//
	// 0.07, not 0.12. At 0.12 a bright sprite competed with the name
	// sitting on top of it — the eye landed on the picture first and had
	// to hunt for the type. A wash should be felt rather than read.
	wash := spriteSVG(art, 26, 44, 44, "0.07")

	// The bar is the whole term, filled by how much of it is left.
	span := expires - registered
	if span < 1 {
		span = 1
	}
	left := expires - now
	if left < 0 {
		left = 0
	}
	if left > span {
		left = span
	}
	fill := (308 * left) / span

	heldLabel := "YEARS HELD"
	if streak == 1 {
		heldLabel = "YEAR HELD"
	}

	/* ---- SAYING IT IS DEAD, LOUDLY ----
	 *
	 * A lapsed card and a live card differed by a border colour and one
	 * word in 12px type at the very bottom. In a wallet's grid they read
	 * as the same purple card — for the one fact that changes what you
	 * can DO with the token: an expired name cannot be sold, cannot be
	 * transferred, and is about to belong to somebody else.
	 *
	 * A wash over the whole card in the status colour, and the status
	 * word on a filled band at nearly twice the size. The band sits at
	 * y=352 because the tenure caption is at 344 and a taller band ate
	 * it; a card that shouts LAPSED and hides how long somebody held it
	 * has traded one fact for another rather than adding one.
	 *
	 * A LIVE CARD IS UNTOUCHED. This must not make the ordinary case
	 * noisier — that is the card somebody paid for.
	 *
	 * Mirrored byte-for-byte in the site's nft.js. If this changes, that
	 * changes, or a preview stops matching what the chain draws. */
	metalDefs, frameStroke, frameWidth := metalFrame(tid, status, edge, streak)

	statusWash, statusBand := "", ""
	if status == "GRACE PERIOD" || status == "LAPSED" {
		washOp := "0.13"
		if status == "LAPSED" {
			washOp = "0.17"
		}
		statusWash = ufmt.Sprintf(
			`<rect width="400" height="400" fill="%s" opacity="%s"/>`, edge, washOp)
		statusBand = ufmt.Sprintf(
			`<rect x="12" y="352" width="376" height="36" fill="%s" opacity="0.92"/>`+
				`<rect x="12" y="352" width="376" height="36" fill="none" stroke="%s" stroke-width="3"/>`+
				`<text x="200" y="378" text-anchor="middle" font-family="monospace" `+
				`font-size="20" font-weight="bold" fill="#1b1200">%s</text>`,
			edge, edge, ribbon)
	}

	body := ufmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" role="img">
  %s<rect width="400" height="400" fill="#10101a"/>
  %s%s
  <rect x="12" y="12" width="376" height="376" rx="18" fill="none" stroke="%s" stroke-width="%s"/>
  <text x="30" y="42" font-family="monospace" font-size="10" fill="%s" opacity="0.7">MINTED ON GNO.LAND</text>
  <text x="370" y="42" text-anchor="end" font-family="monospace" font-size="10" fill="%s" opacity="0.7">SINCE %s</text>
  <text x="200" y="196" text-anchor="middle" font-family="monospace" font-size="%d" font-weight="bold" fill="#ffffff">%s</text>
  <!-- THE STATIC FRAME. A marketplace showing this token as a still
       gets whichever of these two lines is visible with no animation
       running, and that MUST be the date. Everything that matters about
       a name at a glance -- is it live, is it expired, when does it go
       -- is in the date; "412 days left" frozen into a thumbnail is a
       number that was true once and is a lie thereafter.

       It works out that way under both kinds of renderer, which is why
       it is written like this and not any other way:

         a renderer that IGNORES SMIL uses the base attribute in the
         markup, so the date's opacity="1" and the counter's opacity="0"
         decide it

         a renderer that HONOURS SMIL and seeks to t=0 uses the first
         keyTime, so the date's values="1;0" and the counter's "0;1"
         decide it

       Both must keep agreeing. Reorder these two lines, or drop an
       explicit opacity, and the still becomes a countdown -- with
       nothing failing and nothing to notice until a card in somebody
       else's gallery says a name has 412 days left three years from
       now. Guarded by TestStaticFrameShowsTheDate. -->
  <text x="200" y="224" text-anchor="middle" font-family="monospace" font-size="13" fill="%s" opacity="1">%s<animate attributeName="opacity" calcMode="discrete" values="1;0" keyTimes="0;0.5" dur="8s" repeatCount="indefinite"/></text>
  <text x="200" y="224" text-anchor="middle" font-family="monospace" font-size="13" fill="%s" opacity="0">%s<animate attributeName="opacity" calcMode="discrete" values="0;1" keyTimes="0;0.5" dur="8s" repeatCount="indefinite"/></text>
  <rect x="46" y="256" width="308" height="9" rx="4" fill="#ffffff" opacity="0.13"/>
  <rect x="46" y="256" width="%d" height="9" rx="4" fill="%s"/>
  <text x="46" y="282" font-family="monospace" font-size="9" fill="#ffffff" opacity="0.45">%s</text>
  <text x="354" y="282" text-anchor="end" font-family="monospace" font-size="9" fill="#ffffff" opacity="0.45">%s</text>
  <text x="200" y="326" text-anchor="middle" font-family="monospace" font-size="30" font-weight="bold" fill="#ffffff">%d</text>
  <text x="200" y="344" text-anchor="middle" font-family="monospace" font-size="9" fill="%s" opacity="0.8">%s</text>
  %s
  %s
</svg>`,
		metalDefs, wash, statusWash, frameStroke, frameWidth,
		accent, accent, time.Unix(registered, 0).UTC().Format("2006"),
		fitSize(tid), escapeXML(tid),
		accent, time.Unix(expires, 0).UTC().Format("Jan 2, 2006"),
		accent, remaining(expires, now),
		fill, edge,
		time.Unix(registered, 0).UTC().Format("Jan 2006"),
		time.Unix(expires, 0).UTC().Format("Jan 2006"),
		streak, accent, heldLabel,
		smallRibbon(status, edge, ribbon, statusBand),
		overlay)

	/* ---- GRACE AND LAPSED, LAYERED ON TOP ----
	 *
	 * Both branch OUT of `body` rather than building their own copy of
	 * it, on purpose: `body` above is untouched from before this pair of
	 * treatments existed, so a LIVE or FROZEN card -- the two states
	 * that are not supposed to change AT ALL -- takes neither branch and
	 * returns exactly the string it always returned. TestCardUnchangedForLiveAndFrozen
	 * pins that down against a captured pre-change baseline, which is a
	 * stronger guarantee than "I re-read the template and it looks
	 * right" for a template this dense.
	 *
	 * LAPSED only needs one more thing drawn on top, so it is one
	 * strings.Replace of the closing tag.
	 *
	 * GRACE needs three pieces of `body` re-wrapped in place -- the art
	 * wash, the frame-and-header block, and the term bar -- while the
	 * status band and the date line in between are left exactly where
	 * they are. That is done by locating each piece with a FIXED anchor
	 * string from the template above (never a byte offset, and never
	 * anything built from a dynamic value like a colour or a date, so a
	 * future edit to what's IN the template cannot silently point this
	 * at the wrong slice) and splicing a <g> around it. See heartbeat()
	 * and TestGraceHeartbeatLeavesBandAndDateAlone. */
	switch status {
	case "LAPSED":
		return strings.Replace(body, "</svg>", crackOverlay+"</svg>", 1)
	case "GRACE PERIOD":
		return graceHeartbeat(body, statusWash)
	default:
		return body
	}
}

// graceHeartbeat re-wraps three pieces of an already-built grace card in
// the failing-heartbeat flicker, leaving the status band and the date
// line between them untouched. See the "GRACE AND LAPSED, LAYERED ON
// TOP" comment in cardSVG for why this operates on the finished string
// rather than building a second template.
//
// Every anchor here is fixed template text, not a dynamic value, so it
// does not drift when a colour, a date or a name changes -- only when
// the template itself does, and TestGraceHeartbeatLeavesBandAndDateAlone
// would catch that (the -1 guards below make a missed anchor degrade to
// the plain card rather than a corrupted one).
func graceHeartbeat(body, statusWash string) string {
	const bgAnchor = `<rect width="400" height="400" fill="#10101a"/>` + "\n  "
	bgEnd := strings.Index(body, bgAnchor)
	frameStart := strings.Index(body, `<rect x="12" y="12" width="376" height="376" rx="18"`)
	commentStart := strings.Index(body, `<!-- THE STATIC FRAME`)
	barStart := strings.Index(body, `<rect x="46" y="256" width="308" height="9" rx="4" fill="#ffffff" opacity="0.13"/>`)
	bandStart := strings.Index(body, `<rect x="12" y="352"`)
	if bgEnd < 0 || frameStart < 0 || commentStart < 0 || barStart < 0 || bandStart < 0 {
		return body
	}
	washStart := bgEnd + len(bgAnchor)
	washRel := strings.Index(body[washStart:], statusWash)
	if washRel < 0 {
		return body
	}
	washEnd := washStart + washRel

	return body[:washStart] +
		heartbeat(body[washStart:washEnd]) + // the art wash alone
		body[washEnd:frameStart] + // statusWash, held steady
		heartbeat(body[frameStart:commentStart]) + // frame, MINTED/SINCE, the name
		body[commentStart:barStart] + // the STATIC FRAME comment + the date line, held steady
		heartbeat(body[barStart:bandStart]) + // the term bar, both dates, the held count
		body[bandStart:] // the status band onward, held steady
}

// fitSize solves for a size rather than stepping through a ladder.
// Monospace glyphs are ~0.6em, so a name up to the full 32-character
// limit sets on one line without overflowing 336px.
func fitSize(s string) int {
	n := len(s)
	if n < 1 {
		n = 1
	}
	size := 336 * 10 / (6 * n)
	// 40, not 34: the name is the thing somebody bought, and on a card
	// where the drawing sits behind it, the type has to be the loudest
	// object on the tile. Short names were leaving the middle of the card
	// half empty.
	if size > 40 {
		size = 40
	}
	if size < 11 {
		size = 11
	}
	return size
}

// domainAccent reads the accent out of the domain's stored drawing, so
// the card wears the domain's own colour without this realm carrying a
// palette of its own. Falls back to the house colour.
func domainAccent(domainLabel string) string {
	return accentOf(nsdata.GetDomainExtra(domainLabel, keyArt))
}

func accentOf(enc string) string {
	if len(enc) >= 8 && enc[1] == '#' && isHexColour(enc[1:8]) {
		return enc[1:8]
	}
	return "#5eead4"
}

func remaining(expires, now int64) string {
	if now >= expires {
		d := (now - expires) / daySeconds
		if d <= 0 {
			return "expired today"
		}
		if d == 1 {
			return "1 day past due"
		}
		return ufmt.Sprintf("%d days past due", d)
	}
	d := (expires - now) / daySeconds
	if d <= 0 {
		return "expires today"
	}
	if d == 1 {
		return "1 day remaining"
	}
	return ufmt.Sprintf("%d days remaining", d)
}

// keyArt is the per-domain extension key holding the drawing. The value
// is "A#facc15,B#7c2d12|............|....AAAA....|..." — the palette,
// then twelve rows of twelve characters where '.' is transparent.
//
// PARSED DEFENSIVELY AND NEVER TRUSTED. It is written by whichever logic
// realm is current, so a future one could store something malformed;
// anything unexpected yields no sprite rather than broken markup inside
// a token that a marketplace will render.
const keyArt = "art"

func spriteSVG(enc string, px, ox, oy int, opacity string) string {
	if enc == "" {
		return ""
	}
	parts := strings.Split(enc, "|")
	if len(parts) != 13 {
		return ""
	}
	// palette: "A#facc15,B#7c2d12"
	colours := map[string]string{}
	for _, entry := range strings.Split(parts[0], ",") {
		// key + "#" + six hex digits: "A#facc15" is EIGHT characters.
		// This read 7 and rejected every valid sprite; the test caught it.
		if len(entry) != 8 || entry[1] != '#' {
			return ""
		}
		key := entry[:1]
		hex := entry[1:]
		if !isHexColour(hex) {
			return ""
		}
		colours[key] = hex
	}
	var b strings.Builder
	for y := 1; y <= 12; y++ {
		row := parts[y]
		if len(row) != 12 {
			return ""
		}
		for x := 0; x < 12; x++ {
			ch := row[x : x+1]
			if ch == "." {
				continue
			}
			c, ok := colours[ch]
			if !ok {
				return ""
			}
			b.WriteString(ufmt.Sprintf(
				`<rect x="%d" y="%d" width="%d" height="%d" fill="%s"/>`,
				ox+(x*px), oy+((y-1)*px), px, px, c))
		}
	}
	if b.Len() == 0 {
		return ""
	}
	return `<g opacity="` + opacity + `">` + b.String() + `</g>`
}

func isHexColour(s string) bool {
	if len(s) != 7 || s[0] != '#' {
		return false
	}
	for i := 1; i < 7; i++ {
		c := s[i]
		if !(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F') {
			return false
		}
	}
	return true
}

func placeholderSVG(msg string) string {
	return ufmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">`+
		`<rect width="400" height="400" fill="#10101a"/>`+
		`<text x="200" y="200" text-anchor="middle" font-family="monospace" font-size="18" fill="#666680">%s</text></svg>`,
		escapeXML(msg))
}

// statusFields formats a lifecycle state for display. Reads the grace
// period from nsdata rather than hardcoding it, so retuning the lifecycle
// is a config change and this stays correct.
// All lifecycle times are unix seconds, so this is integer arithmetic
// over a day constant rather than duration division.
const daySeconds = int64(24 * 60 * 60)

/* ---- THE METAL LADDER ----
 *
 * From the "Name States" study, 2026-08-23, where it was designed and
 * then not built for a fortnight. One rung per year held, carried by the
 * frame: 1 bronze, 2 silver, 3 gold, 4 platinum, 5+ diamond.
 *
 * THE LADDER IS PICKED FOR SEPARATION, not for what the metals are
 * worth. Brown, then cool grey, then yellow, then warm white, then
 * something that is not a metal at all. The obvious ladder — silver,
 * platinum, rhodium — is three whitish metals in a row, and nobody can
 * tell year two from year five across a grid of thumbnails. Platinum is
 * pulled deliberately WARM to keep it off the gold below it.
 *
 * The highlight travels faster at the higher rungs, so a longer-held
 * name reads as brighter as well as merely different.
 *
 * DIAMOND IS SATURATED AND KEEPS ITS WHITE. Fire in a real stone is
 * spectral colour separated BY white; take the white bands out and it
 * stops reading as a gem and starts reading as an oil slick.
 *
 * IT ADDS NO WORDS. The ribbon has said DIAMOND HANDS since year one and
 * at year five the card finally makes good on it. The domain's own
 * colour still runs through the type and the term bar, so a name reads
 * as its domain first and its tenure second.
 *
 * YEAR ZERO GETS NO METAL, which is the whole point of a ladder: if a
 * new name looked decorated, the rungs a name EARNS would mean nothing.
 *
 * Mirrored in the site's nft.js. These two move together or a preview
 * stops matching what the chain draws.
 */
type metal struct {
	dur   int
	stops string // already-rendered <stop> elements
}

func metalFor(streak int64) (metal, bool) {
	switch {
	case streak <= 0:
		return metal{}, false
	case streak == 1:
		return metal{13, `<stop offset="0%" stop-color="#3a1c0c"/><stop offset="32%" stop-color="#e6b088"/>` +
			`<stop offset="52%" stop-color="#b87333"/><stop offset="100%" stop-color="#3a1c0c"/>`}, true
	case streak == 2:
		return metal{11, `<stop offset="0%" stop-color="#3f4650"/><stop offset="32%" stop-color="#f1f5f9"/>` +
			`<stop offset="52%" stop-color="#aab4c0"/><stop offset="100%" stop-color="#3f4650"/>`}, true
	case streak == 3:
		return metal{9, `<stop offset="0%" stop-color="#6b2f0a"/><stop offset="32%" stop-color="#fde68a"/>` +
			`<stop offset="52%" stop-color="#f59e0b"/><stop offset="100%" stop-color="#6b2f0a"/>`}, true
	case streak == 4:
		return metal{9, `<stop offset="0%" stop-color="#6b6357"/><stop offset="30%" stop-color="#fbf7ef"/>` +
			`<stop offset="50%" stop-color="#ddd4c4"/><stop offset="100%" stop-color="#6b6357"/>`}, true
	default:
		return metal{5, `<stop offset="0%" stop-color="#0369a1"/><stop offset="16%" stop-color="#ffffff"/>` +
			`<stop offset="30%" stop-color="#22d3ee"/><stop offset="44%" stop-color="#ffffff"/>` +
			`<stop offset="58%" stop-color="#e879f9"/><stop offset="72%" stop-color="#ffffff"/>` +
			`<stop offset="86%" stop-color="#38bdf8"/><stop offset="100%" stop-color="#0369a1"/>`}, true
	}
}

/*
metalFrame returns the <defs>, the stroke and the stroke width for a
card, or the plain versions when no metal is earned.

THE METAL ONLY APPLIES TO A LIVE NAME. A gilded frame around a lapsed
card would celebrate a name that is about to belong to somebody else, and
it would fight the red wash that exists to say so. Grace and lapsed lose
the metal, which is itself information: the frame going plain is the
tenure visibly at risk.

THE GRADIENT ID CARRIES THE TOKEN. A Render() page draws many of these
into one document and SVG resolves url(#id) document-wide, so a fixed id
would make every card after the first wear the first card's metal. The
token id is unique by construction; it is sanitised because "*" and "-"
are not valid in an id.
*/
func metalFrame(tid, status, edge string, streak int64) (defs, stroke, width string) {
	m, ok := metalFor(streak)
	if !ok || status != "LIVE" {
		return "", edge, "3"
	}
	id := "m" + idSafe(tid)
	defs = ufmt.Sprintf(
		`<defs><linearGradient id="%s" x1="0" y1="0" x2="1" y2="1">%s`+
			`<animateTransform attributeName="gradientTransform" type="rotate" `+
			`from="0 .5 .5" to="360 .5 .5" dur="%ds" repeatCount="indefinite"/>`+
			`</linearGradient></defs>`, id, m.stops, m.dur)
	return defs, "url(#" + id + ")", "4"
}

// An XML id may not contain "*", and a name may not contain anything
// else that would need escaping — the registry's own label rules see to
// that — so one substitution is enough.
func idSafe(tid string) string {
	return strings.ReplaceAll(tid, "*", "-")
}

// The foot of the card: a quiet ribbon while the name is alive, the loud
// band once it is not. One function so the two cannot both be drawn.
func smallRibbon(status, edge, ribbon, band string) string {
	if band != "" {
		return band
	}
	return ufmt.Sprintf(
		`<text x="200" y="372" text-anchor="middle" font-family="monospace" `+
			`font-size="12" font-weight="bold" fill="%s">%s</text>`, edge, ribbon)
}

/* ---- FAILING HEARTBEAT (grace period) ----
 *
 * From the "Name States" study, 2026-08-23 -- the "Failing heartbeat"
 * treatment, built around pulses()/BURSTS/track() there. Bursts of two,
 * one, three and one flash at 0.02/0.30/0.55/0.80 of a 7.5s cycle read
 * as an unpredictable fault rather than an even, designed blink, so the
 * rhythm carries over unchanged. graceValues and graceKeyTimes below are
 * that generator's output for base=1, dip=0.25 -- computed once, not
 * rebuilt on every read, since a fixed rhythm shared by every grace card
 * on the chain has nothing left to vary.
 *
 * INVERTED FROM THE STUDY, and deliberately. There the track sits DARK
 * and briefly flashes LIT -- fine for something animating live in a
 * browser tab, useless for a marketplace that renders one still frame:
 * the base opacity in the markup and the first keyframe are BOTH the
 * dark value there, so a still render of that track is nearly
 * invisible. Here the rest state is fully lit -- opacity 1, exactly the
 * live card -- and the bursts are brief DIPS toward .25 instead, so
 * whichever still a renderer takes (the base attribute for one that
 * ignores SMIL, the first keyframe for one that honours it) lands on
 * the fully-lit card. graceValues therefore reads "1;1;0.25;..." and
 * graceKeyTimes starts "0.0000;...": both a "1" at index zero, on
 * purpose. TestGraceHeartbeatLeavesBandAndDateAlone checks exactly that.
 *
 * Mirrored in the site's nft.js (pulseTrack/heartbeat there, same two
 * numbers). If this changes, that changes, or a preview stops matching
 * what the chain draws.
 */
const graceValues = "1;1;0.25;0.25;1;1;0.25;0.25;1;1;0.25;0.25;1;1;0.25;0.25;1;1;0.25;0.25;1;1;0.25;0.25;1;1;0.25;0.25;1;1"
const graceKeyTimes = "0.0000;0.0200;0.0240;0.0350;0.0390;0.0570;0.0610;0.0720;0.0760;0.3000;0.3040;0.3150;0.3190;0.5500;0.5540;0.5650;0.5690;0.5870;0.5910;0.6020;0.6060;0.6240;0.6280;0.6390;0.6430;0.8000;0.8040;0.8150;0.8190;1.0000"

// heartbeat wraps one piece of a grace card in the failing-heartbeat
// flicker. Called three separate times in graceHeartbeat rather than
// once around the whole card, so the status band and the date line can
// sit between the wrapped pieces untouched. Every call shares the same
// values/keyTimes/dur; SMIL times every <animate> from document load, so
// three separate <g>s stay in lockstep without needing to share one.
func heartbeat(inner string) string {
	return `<g opacity="1">` + inner +
		`<animate attributeName="opacity" values="` + graceValues +
		`" keyTimes="` + graceKeyTimes + `" dur="7.5s" repeatCount="indefinite"/></g>`
}

/* ---- CRACKED (lapsed) ----
 *
 * From the same study, under LAPSED. Static, no animation: a fracture
 * across the glass with two short branches, drawn last so it sits over
 * everything else on the card; the art behind it is untouched and
 * undimmed.
 *
 * THE STUDY'S PATH IS NOT USED AS-IS. Its middle segment runs through
 * x=140-176 at y=168-214 -- dead centre, right through where the name
 * sits on the study's fixed-width demo cards. That is not fine here:
 * the name is centred on x=200 with text-anchor="middle" and can run up
 * to 32 characters (see fitSize), so its box can span nearly the full
 * card width -- as far out as roughly x=30 to x=370 -- for a long one.
 * No amount of routing the crack sideways dodges that band, because a
 * long enough name is somewhere underneath any vertical line drawn
 * across it.
 *
 * So the crack is drawn as two pieces rather than one continuous line:
 * an upper fracture that stays above y=158 and a lower one that stays
 * below y=224, leaving the name's row (166-206) and the date line under
 * it (214-228) untouched regardless of how long the name is. It reads
 * as the fracture running into the nameplate and continuing on the far
 * side, rather than through it -- arguably truer to how a crack behaves
 * against a raised, painted surface anyway. Other type on the card (the
 * term bar, the held count) is still legitimately crossed, same as in
 * the study; only the name and the date get the gap.
 *
 * Mirrored byte-for-byte in the site's nft.js (CRACK_OVERLAY there).
 */
const crackOverlay = `<g stroke="#ffffff" fill="none" opacity="0.5" stroke-width="2">` +
	`<path d="M92 24 L150 72 L112 118 L162 152"/>` +
	`<path d="M112 118 L54 138"/>` +
	`<path d="M158 224 L206 270 L172 318 L228 388"/>` +
	`<path d="M172 318 L268 300"/>` +
	`</g>` +
	`<g stroke="#000000" fill="none" opacity="0.35" stroke-width="4">` +
	`<path d="M94 26 L152 74 L114 120 L164 154"/>` +
	`<path d="M160 226 L208 272 L174 320 L230 390"/>` +
	`</g>`

func statusFields(expires int64, frozen bool) (status, edge string) {
	if frozen {
		return "FROZEN", "#8888aa"
	}
	now := time.Now().Unix()
	grace := nsdata.GetGracePeriod()
	switch {
	case now < expires:
		return "LIVE", "#4ade80"
	case now < expires+grace:
		return "GRACE PERIOD", "#facc15"
	default:
		return "LAPSED", "#f87171"
	}
}

func escapeXML(s string) string {
	s = strings.ReplaceAll(s, "&", "&amp;")
	s = strings.ReplaceAll(s, "<", "&lt;")
	s = strings.ReplaceAll(s, ">", "&gt;")
	s = strings.ReplaceAll(s, `"`, "&quot;")
	return s
}