package connector

import (
	"bytes"
	"context"
	"crypto/md5"
	"encoding/binary"
	"fmt"
	"image"
	"image/color"
	"image/draw"
	_ "image/gif"
	_ "image/jpeg"
	"image/png"
	"math"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
	"unicode"

	xdraw "golang.org/x/image/draw"
	"golang.org/x/image/math/fixed"
	"golang.org/x/image/font/basicfont"
	"golang.org/x/net/publicsuffix"

	"maunium.net/go/mautrix/bridgev2"
	"maunium.net/go/mautrix/bridgev2/networkid"
)

// avatarAlgoVersion is part of the networkid.AvatarID on purpose:
// bridgev2's ghost.prepareAvatar() short-circuits when the avatar ID is
// unchanged AND the ghost already has an MXC. Bumping this string forces a
// re-fetch + re-upload of every ghost avatar after the algorithm changes.
const avatarAlgoVersion = "v6"

// googleS2Size is the size requested from Google s2. sz=128 is not Google's
// ceiling: sz=256 was measured live on 2026-10-01 and returns strictly larger
// images (uber.com 128->180, stripe.com 128->256) while never falling back to a
// placeholder the way sz=512 does (512 answered 16x16 for every domain tested).
const googleS2Size = 256

type avatarCandidate struct {
	URL      string
	Kind     string
	AllowHTTP bool // also try plain http:// if the https:// attempt fails
}

// avatarCandidates builds the ordered candidate list for an email address.
//
// Order rationale (all entries verified live on 2026-09-29):
//
//	1. Gravatar                        -> the only source that is really per-person
//	2. <domain>/favicon.ico            -> most sites serve a real brand icon
//	3. <domain>/apple-touch-icon.png   -> high-res PNG, better than the .ico
//	4. Google s2                        -> huge index, 128px PNG
//	5. DuckDuckGo icons                 -> different index than Google
//	6. <registrable domain>/...         -> true DNS ancestor, e.g.
//	                                      mail.kleinanzeigen.de -> kleinanzeigen.de
//	7. <brand alias>/...                -> explicit config mapping for providers
//	                                      whose mail domain is a separate
//	                                      registration: luma-mail.com -> luma.com
//	8. unavatar.io aggregator           -> last remote hope (its letter-fallback
//	                                      SVG is rejected, we build our own)
//	9. local generic identicon          -> never fails, clearly generic
func avatarCandidates(email string, aliases map[string]string) []avatarCandidate {
	email = strings.ToLower(strings.TrimSpace(email))
	sum := md5.Sum([]byte(email))
	out := []avatarCandidate{{
		URL:  fmt.Sprintf("https://www.gravatar.com/avatar/%x?s=256&d=404", sum),
		Kind: "gravatar",
	}}

	domain := hostnameOfEmail(email)
	if domain == "" && looksLikeDomain(email) {
		// The mail connector also creates "domain ghosts" (networkid.UserID is
		// just the sender domain, e.g. "user.luma-mail.com", no local part).
		// Without this, every such ghost skipped the whole favicon cascade and
		// landed on the placeholder even though the logo was available.
		domain = email
	}
	if domain == "" {
		return out
	}
	out = append(out, domainCandidates(domain)...)
	for _, alt := range brandDomainChain(domain, aliases) {
		out = append(out, domainCandidates(alt)...)
	}
	out = append(out, avatarCandidate{
		URL:  "https://unavatar.io/" + domain,
		Kind: "unavatar",
	})
	return out
}

func domainCandidates(domain string) []avatarCandidate {
	return []avatarCandidate{
		{URL: "https://" + domain + "/favicon.ico", Kind: "direct-ico", AllowHTTP: true},
		{URL: "https://" + domain + "/apple-touch-icon.png", Kind: "direct-atp", AllowHTTP: true},
		{URL: "https://www.google.com/s2/favicons?sz=" + strconv.Itoa(googleS2Size) + "&domain=" + url.QueryEscape(domain), Kind: "google"},
		{URL: "https://icons.duckduckgo.com/ip3/" + domain + ".ico", Kind: "ddg"},
	}
}

// defaultBrandAliases maps mail-host domains that are a *separate* DNS
// registration away from the company that actually owns the brand.
//
// Guessing this automatically would be wrong (stripping "mail" out of
// "foo-mail.com" and loading "foo.com" can easily show a completely unrelated
// company's logo), so the list is explicit and reviewable. Extend it in
// /etc/mautrix/mail/config.yaml under `avatar_brand_aliases`.
var defaultBrandAliases = map[string]string{
	"luma-mail.com": "luma.com",
}

// brandDomainChain returns the additional domains to try after the mail domain
// itself, most specific first:
//
//	a) the eTLD+1, a true DNS ancestor       (mail.kleinanzeigen.de -> kleinanzeigen.de)
//	b) the explicit brand alias for that apex (luma-mail.com            -> luma.com)
func brandDomainChain(domain string, aliases map[string]string) []string {
	domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
	if domain == "" {
		return nil
	}
	out := make([]string, 0, 2)
	apex := registrableDomain(domain)
	if apex != "" && apex != domain {
		out = append(out, apex)
	}
	lookup := aliases
	if lookup == nil {
		lookup = defaultBrandAliases
	}
	for _, key := range []string{domain, apex} {
		if key == "" {
			continue
		}
		if target := strings.ToLower(strings.TrimSpace(lookup[key])); target != "" && target != domain && !containsString(out, target) {
			out = append(out, target)
		}
	}
	return out
}

// looksLikeDomain reports whether s is a bare hostname (no local part) that is
// worth running through the favicon cascade.
func looksLikeDomain(s string) bool {
	if !strings.Contains(s, ".") || strings.ContainsAny(s, " @/\\") {
		return false
	}
	labels := strings.Split(s, ".")
	if len(labels) < 2 {
		return false
	}
	for _, l := range labels {
		if l == "" {
			return false
		}
	}
	return true
}

func containsString(hay []string, needle string) bool {
	for _, h := range hay {
		if h == needle {
			return true
		}
	}
	return false
}


// registrableDomain returns the eTLD+1 ("luma-mail.com" for "user.luma-mail.com").
func registrableDomain(domain string) string {
	domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
	if domain == "" || net_IsIP(domain) {
		return ""
	}
	apex, err := publicsuffix.EffectiveTLDPlusOne(domain)
	if err != nil || apex == "" {
		// fall back to a naive "last two labels" heuristic
		parts := strings.Split(domain, ".")
		if len(parts) < 2 {
			return ""
		}
		return strings.Join(parts[len(parts)-2:], ".")
	}
	return apex
}

func net_IsIP(s string) bool {
	if s == "" {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if c != '.' && c != ':' && (c < '0' || c > '9') {
			return false
		}
	}
	return true
}

func (c *MailClient) avatarFor(email string) *bridgev2.Avatar {
	email = strings.ToLower(strings.TrimSpace(email))
	var aliases map[string]string
	if c.Connector != nil && c.Connector.Config != nil {
		aliases = c.Connector.Config.AvatarBrandAliases
	}
	candidates := avatarCandidates(email, aliases)
	avlog := c.Log.With().Str("email", email).Logger()

	return &bridgev2.Avatar{
		ID: networkid.AvatarID(avatarAlgoVersion + ":" + email),
		Get: func(ctx context.Context) ([]byte, error) {
			// Hard cap on the whole cascade: a single bridge restart must not
			// spend minutes per ghost. ~9 candidates x 8s would be 72s.
			budget, cancel := context.WithTimeout(ctx, avatarTotalBudget)
			defer cancel()

			var lastErr error
			var tinyFallback []byte
			var best []byte
			var bestSide int
			for _, cand := range candidates {
				data, err := fetchImage(budget, cand.URL)
				if err != nil && cand.AllowHTTP {
					// Some hosts have a completely broken TLS stack (we saw
					// messe-jobs.de answer every ClientHello with TLS alert 80
					// "internal error" on both v4 and v6). Plain HTTP still works.
					if plain := toHTTPURL(cand.URL); plain != "" {
						if d2, err2 := fetchImage(budget, plain); err2 == nil {
							data, err = d2, nil
						}
					}
				}
				if err != nil {
					lastErr = err
					avlog.Debug().Err(err).Str("source", cand.Kind).Str("url", cand.URL).
						Msg("Avatar candidate failed")
					continue
				}
				data, err = normalizeAvatarImage(data)
				if err != nil {
					lastErr = err
					avlog.Debug().Err(err).Str("source", cand.Kind).Str("url", cand.URL).
						Msg("Avatar image rejected")
					continue
				}
				// A 16x16 favicon is technically a success but looks like
				// mush in a room list. Keep it only as a last resort: remember
				// it and keep looking for a larger source first.
				if imageTooSmall(data) {
					if tinyFallback == nil {
						tinyFallback = data
					}
					avlog.Debug().Str("source", cand.Kind).Str("url", cand.URL).
						Msg("Avatar candidate too small, trying next source")
					continue
				}
				// Take the LARGEST candidate, not the first acceptable one.
				// <domain>/favicon.ico routinely answers 48x48 while Google s2
				// has 180x256 for the same domain, and the .ico sits earlier in
				// the cascade. Returning on the first hit pinned those rooms to
				// 48px even though a sharp logo was one request away.
				if side, _, err := imageSideAndFormat(data); err == nil {
					if side > bestSide {
						bestSide = side
						best = data
					}
				} else if best == nil {
					best = data
				}
			}
			if best != nil {
				avlog.Info().
					Str("source", "best-of").
					Int("side", bestSide).
					Int("bytes", len(best)).
					Msg("Mail avatar resolved")
				return best, nil
			}
			// Everything on the net was a tiny favicon. Better a smoothly
			// upscaled one than no avatar at all.
			if tinyFallback != nil {
				if up, err := upscaleIfTiny(tinyFallback); err == nil {
					avlog.Info().Int("bytes", len(up)).
						Msg("Mail avatar: upscaled tiny favicon")
					return up, nil
				}
			}
			if lastErr == nil {
				lastErr = fmt.Errorf("no avatar candidates")
			}
			// Nothing on the net worked. Rather than leaving the room bare we
			// generate a deterministic local placeholder. It is NOT a real logo.
			generic := generateGenericAvatar(email)
			avlog.Info().
				Int("bytes", len(generic)).
				Err(lastErr).
				Msg("Mail avatar: using locally generated GENERIC identicon (no real logo available)")
			return generic, nil
		},
	}
}

const (
	avatarPerURLTimeout = 8 * time.Second
	avatarTotalBudget   = 25 * time.Second
	avatarMaxBody       = 2 << 20
)

var avatarHTTPClient = &http.Client{
	Timeout: avatarPerURLTimeout,
	Transport: &http.Transport{
		MaxIdleConns:        16,
		IdleConnTimeout:     30 * time.Second,
		TLSHandshakeTimeout: 6 * time.Second,
		DisableKeepAlives:   false,
	},
}

func toHTTPURL(u string) string {
	p, err := url.Parse(u)
	if err != nil || p.Scheme != "https" {
		return ""
	}
	p.Scheme = "http"
	return p.String()
}

func fetchImage(ctx context.Context, rawURL string) ([]byte, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; mautrix-mail-bridge/1.0; +https://marlonivo.com)")
	req.Header.Set("Accept", "image/png,image/jpeg,image/*;q=0.8")
	resp, err := avatarHTTPClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("GET %s: %s", rawURL, resp.Status)
	}
	data, err := io.ReadAll(io.LimitReader(resp.Body, avatarMaxBody))
	if err != nil {
		return nil, err
	}
	if len(data) < 64 {
		return nil, fmt.Errorf("GET %s: body too small (%d bytes)", rawURL, len(data))
	}
	return data, nil
}

// normalizeAvatarImage makes sure we only ever hand bridgev2 a real
// raster image that a Matrix client can actually paint.
//
// This matters: uber.com/hetzner.com/stripe.com/favicon.ico return genuine
// Windows .ico containers (verified: bytes 00 00 01 00 ...). Those were
// uploaded as image/x-icon and no client ever rendered them, so the avatar
// was effectively invisible even though the fetch "succeeded".
// avatarMinUsableSide is the smallest edge length we accept without complaint.
//
// Real favicons are routinely 16x16. Uploading such a bitmap 1:1 is what made
// half the room avatars look like pixel soup, so anything smaller than this is
// treated as a failure and the cascade continues to the next (usually larger)
// source. Only if *every* candidate is tiny do we fall back to upscaling.
const avatarMinUsableSide = 48

// avatarUpscaleTarget is the side length tiny icons are blown up to.
const avatarUpscaleTarget = 128

// imageSideAndFormat decodes data enough to know its pixel dimensions.
// Returns the long edge and whether data was a decodable raster image.
func imageSideAndFormat(data []byte) (int, string, error) {
	cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
	if err != nil {
		return 0, "", err
	}
	side := cfg.Width
	if cfg.Height > side {
		side = cfg.Height
	}
	return side, format, nil
}

// upscaleIfTiny blows a too-small favicon up to avatarUpscaleTarget using
// CatmullRom interpolation. Nearest-neighbour would just make the same 16
// pixels bigger, which is exactly the "verpixelt" look we are fixing.
func upscaleIfTiny(data []byte) ([]byte, error) {
	src, _, err := image.Decode(bytes.NewReader(data))
	if err != nil {
		return nil, fmt.Errorf("decode for upscale failed: %w", err)
	}
	b := src.Bounds()
	side := b.Dx()
	if b.Dy() > side {
		side = b.Dy()
	}
	if side >= avatarUpscaleTarget {
		return data, nil
	}
	dst := image.NewNRGBA(image.Rect(0, 0, avatarUpscaleTarget, avatarUpscaleTarget))
	xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, b, xdraw.Over, nil)
	var buf bytes.Buffer
	if err := png.Encode(&buf, dst); err != nil {
		return nil, fmt.Errorf("encode upscaled png: %w", err)
	}
	return buf.Bytes(), nil
}

// imageTooSmall reports whether data is a valid but unusably small raster.
func imageTooSmall(data []byte) bool {
	side, _, err := imageSideAndFormat(data)
	return err == nil && side < avatarMinUsableSide
}

func normalizeAvatarImage(data []byte) ([]byte, error) {
	if isICO(data) {
		pngData, err := icoToPNG(data)
		if err != nil {
			return nil, fmt.Errorf("ico conversion failed: %w", err)
		}
		return pngData, nil
	}
	mime := http.DetectContentType(data)
	switch {
	case strings.HasPrefix(mime, "image/png"), strings.HasPrefix(mime, "image/jpeg"),
		strings.HasPrefix(mime, "image/gif"), strings.HasPrefix(mime, "image/webp"):
		return data, nil
	case strings.HasPrefix(mime, "image/svg"):
		// unavatar.io answers unknown domains with a 200 + letter SVG. We do not
		// upload SVG to Matrix (clients ignore it, and it is an XSS vector), and
		// we generate our own placeholder further down anyway.
		return nil, fmt.Errorf("svg is not usable as a Matrix avatar")
	default:
		return nil, fmt.Errorf("not an image (%s)", mime)
	}
}

func isICO(data []byte) bool {
	if len(data) < 6 {
		return false
	}
	// ICONDIR: reserved=0, type=1 (icon) or 2 (cursor)
	if data[0] == 0 && data[1] == 0 && (data[2] == 1 || data[2] == 2) {
		// Embedded PNG-in-ICO is a valid modern ICO too; let the caller handle it.
		return true
	}
	return false
}

// icoToPNG decodes the largest image inside an .ico container and re-encodes it
// as PNG. Handles both modern PNG-in-ICO and classic BMP-in-ICO.
func icoToPNG(data []byte) ([]byte, error) {
	if len(data) < 6 {
		return nil, fmt.Errorf("too short")
	}
	count := int(binary.LittleEndian.Uint16(data[4:6]))
	if count == 0 || count > 64 {
		return nil, fmt.Errorf("bad image count %d", count)
	}
	type entry struct {
		offset, size int
	}
	entries := make([]entry, 0, count)
	for i := 0; i < count; i++ {
		base := 6 + i*16
		if base+16 > len(data) {
			return nil, fmt.Errorf("truncated directory")
		}
		w := int(data[base])
		h := int(data[base+1])
		if w == 0 {
			w = 256
		}
		if h == 0 {
			h = 256
		}
		size := int(binary.LittleEndian.Uint32(data[base+8 : base+12]))
		offset := int(binary.LittleEndian.Uint32(data[base+12 : base+16]))
		entries = append(entries, entry{offset: offset, size: size})
		_ = w
		_ = h
	}
	// Prefer a PNG payload (cheap, lossless). Only if there is none do we
	// decode the BMP payloads, and then we pick the LARGEST one: an .ico
	// routinely carries 16/32/48/96px variants and taking the first one gives
	// a 16x16 avatar that looks like mush in a room list.
	var best image.Image
	for _, e := range entries {
		if e.offset < 0 || e.offset+e.size > len(data) || e.size < 8 {
			continue
		}
		payload := data[e.offset : e.offset+e.size]
		if http.DetectContentType(payload) == "image/png" {
			return payload, nil
		}
	}
	for _, e := range entries {
		if e.offset < 0 || e.offset+e.size > len(data) || e.size < 40 {
			continue
		}
		img, err := decodeBMPIcon(data[e.offset : e.offset+e.size])
		if err != nil {
			continue
		}
		if best == nil || img.Bounds().Dx()*img.Bounds().Dy() > best.Bounds().Dx()*best.Bounds().Dy() {
			best = img
		}
	}
	if best == nil {
		return nil, fmt.Errorf("no usable image in ico")
	}
	return encodePNG(best)
}

// decodeBMPIcon decodes the ICO flavour of a DIB: 40-byte BITMAPINFOHEADER with
// height = 2 * image height (XOR mask + AND mask), 32bpp BGRA bottom-up.
func decodeBMPIcon(b []byte) (image.Image, error) {
	if len(b) < 40 {
		return nil, fmt.Errorf("too short")
	}
	headerSize := int(binary.LittleEndian.Uint32(b[0:4]))
	if headerSize < 40 || headerSize > len(b) {
		return nil, fmt.Errorf("bad header size %d", headerSize)
	}
	w := int(int32(binary.LittleEndian.Uint32(b[4:8])))
	h := int(int32(binary.LittleEndian.Uint32(b[8:12])))
	planes := binary.LittleEndian.Uint16(b[12:14])
	bpp := binary.LittleEndian.Uint16(b[14:16])
	if planes != 1 {
		return nil, fmt.Errorf("unsupported planes %d", planes)
	}
	if w <= 0 || h <= 0 || w > 1024 || h > 2048 {
		return nil, fmt.Errorf("bad dimensions %dx%d", w, h)
	}
	realH := h / 2
	if realH <= 0 {
		realH = h
	}
	var palette color.Palette
	switch bpp {
	case 1, 4, 8:
		ncolors := 0
		if bpp == 8 {
			ncolors = 256
		} else if bpp == 4 {
			ncolors = 16
		} else {
			ncolors = 2
		}
		if clrUsed := int(binary.LittleEndian.Uint32(b[32:36])); clrUsed > 0 && clrUsed <= ncolors {
			ncolors = clrUsed
		}
		palette = make(color.Palette, ncolors)
		for i := 0; i < ncolors; i++ {
			off := headerSize + i*4
			if off+4 > len(b) {
				return nil, fmt.Errorf("truncated palette")
			}
			palette[i] = color.RGBA{b[off+2], b[off+1], b[off], 0xFF}
		}
	case 24, 32:
	default:
		return nil, fmt.Errorf("unsupported bpp %d", bpp)
	}
	rowSize := ((int(bpp)*w + 31) / 32) * 4
	pixStart := headerSize
	if palette != nil {
		pixStart = headerSize + len(palette)*4
	}
	if pixStart+rowSize*realH > len(b) {
		return nil, fmt.Errorf("truncated pixel data")
	}
	img := image.NewNRGBA(image.Rect(0, 0, w, realH))
	for y := 0; y < realH; y++ {
		srcRow := pixStart + (realH-1-y)*rowSize // BMP is bottom-up
		for x := 0; x < w; x++ {
			var c color.Color
			switch bpp {
			case 32:
				off := srcRow + x*4
				a := b[off+3]
				// .ico 32bpp alpha of 0 means "fully opaque" in many encoders
				if a == 0 {
					a = 0xFF
				}
				c = color.RGBA{b[off+2], b[off+1], b[off], a}
			case 24:
				off := srcRow + x*3
				c = color.RGBA{b[off+2], b[off+1], b[off], 0xFF}
			default:
				perByte := 8 / int(bpp)
				idx := b[srcRow+x/perByte]
				shift := uint(8 - int(bpp)*(x%perByte+1))
				ci := (idx >> shift) & ((1 << uint(bpp)) - 1)
				if int(ci) < len(palette) {
					c = palette[ci]
				} else {
					c = color.Black
				}
			}
			img.SetNRGBA(x, y, color.NRGBAModel.Convert(c).(color.NRGBA))
		}
	}
	return img, nil
}

func encodePNG(img image.Image) ([]byte, error) {
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

const genericAvatarSize = 128

// generateGenericAvatar builds a deterministic, purely local placeholder:
// a 5x5 symmetric colour pattern in a hue derived from the address, with the
// first letter of the local part drawn on top.
//
// It is deliberately NOT a real logo and carries no third-party data.
func generateGenericAvatar(email string) []byte {
	email = strings.ToLower(strings.TrimSpace(email))
	sum := md5.Sum([]byte(email))
	hue := float64(sum[0])/255.0*360.0 + float64(sum[1])/255.0*60.0
	bg := hsl(hue, 0.42, 0.20)
	fg := hsl(hue, 0.62, 0.55)

	const cells = 5
	const margin = 6
	cell := (genericAvatarSize - 2*margin) / cells

	img := image.NewNRGBA(image.Rect(0, 0, genericAvatarSize, genericAvatarSize))
	draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)

	// Mirror the left 3 columns onto the right to get a symmetric pattern.
	for col := 0; col < 3; col++ {
		for row := 0; row < cells; row++ {
			if (sum[(2+row*3+col)%len(sum)] & 1) == 0 {
				continue
			}
			x0 := margin + col*cell
			y0 := margin + row*cell
			for dx := 0; dx < cell; dx++ {
				for _, x := range []int{x0 + dx, genericAvatarSize - margin - (col+1)*cell + dx} {
					draw.Draw(img, image.Rect(x, y0, x+1, y0+cell),
						&image.Uniform{fg}, image.Point{}, draw.Src)
				}
			}
		}
	}

	// Letter on a solid plate so it stays readable on any pattern.
	letter := avatarInitial(email)
	drawLetter(img, letter, bg, fg)
	if out, err := encodePNG(img); err == nil {
		return out
	}
	// Last-resort 1x1 PNG should be impossible, but never return nil.
	imgOut, _ := encodePNG(image.NewNRGBA(image.Rect(0, 0, 1, 1)))
	return imgOut
}

func avatarInitial(email string) rune {
	local, _, _ := strings.Cut(email, "@")
	for _, r := range local {
		if unicode.IsLetter(r) || unicode.IsDigit(r) {
			return unicode.ToUpper(r)
		}
	}
	return '?'
}

func drawLetter(img *image.NRGBA, letter rune, bg, fg color.Color) {
	const platePad = 8

	face := basicfont.Face7x13
	gw, gh := face.Width, face.Ascent+face.Descent
	if gw <= 0 || gh <= 0 {
		return
	}
	_, mask, maskp, _, ok := face.Glyph(fixed.Point26_6{}, letter)
	if !ok || mask == nil {
		return
	}

	const glyphScale = 5
	tw := gw * glyphScale
	th := gh * glyphScale
	if tw+2*platePad >= genericAvatarSize || th+2*platePad >= genericAvatarSize {
		return
	}
	x0 := (genericAvatarSize - tw) / 2
	y0 := (genericAvatarSize - th) / 2
	draw.Draw(img,
		image.Rect(x0-platePad, y0-platePad, x0+tw+platePad, y0+th+platePad),
		&image.Uniform{bg}, image.Point{}, draw.Src)

	for gy := 0; gy < gh; gy++ {
		for gx := 0; gx < gw; gx++ {
			_, _, _, a := mask.At(maskp.X+gx, maskp.Y+gy).RGBA()
			if a == 0 {
				continue
			}
			px := x0 + gx*glyphScale
			py := y0 + gy*glyphScale
			draw.Draw(img, image.Rect(px, py, px+glyphScale, py+glyphScale),
				&image.Uniform{fg}, image.Point{}, draw.Src)
		}
	}
}

func hsl(h, s, l float64) color.RGBA {
	c := (1 - absFloat(2*l-1)) * s
	hp := h / 60.0
	if hp >= 6 {
		hp = 0
	}
	x := c * (1 - absFloat(math.Mod(hp, 2)-1))
	var r, g, b float64
	switch {
	case hp < 1:
		r, g, b = c, x, 0
	case hp < 2:
		r, g, b = x, c, 0
	case hp < 3:
		r, g, b = 0, c, x
	case hp < 4:
		r, g, b = 0, x, c
	case hp < 5:
		r, g, b = x, 0, c
	default:
		r, g, b = c, 0, x
	}
	m := l - c/2
	return color.RGBA{
		R: uint8((r + m) * 255),
		G: uint8((g + m) * 255),
		B: uint8((b + m) * 255),
		A: 0xFF,
	}
}

func absFloat(f float64) float64 {
	if f < 0 {
		return -f
	}
	return f
}
