"""Drawing toolkit for the breadboard guide: boards, modules, parts and wires as SVG strings.

Coordinates: a Board has its own origin at hole (column 1, row j). One breadboard hole pitch
(0.1 inch) is P pixels. Row letters follow the usual breadboard layout: j..f above the centre
channel, e..a below it, with two power rails above and two below.
"""
import math

P = 14.0                 # pixels per 0.1 inch
S = P / 2.54             # pixels per millimetre
COLS = 63

ROW = {"j": 0, "i": 1, "h": 2, "g": 3, "f": 4, "e": 7, "d": 8, "c": 9, "b": 10, "a": 11,
       "T1": -3.0, "T2": -2.0, "B1": 13.0, "B2": 14.0}

# wire colours: (fill, outline)
COL = {
    "red": ("#e63946", "#8f1d27"), "rose": ("#ff6f91", "#b23a5a"), "orange": ("#f48c06", "#9c5a00"),
    "black": ("#33363b", "#111214"), "blue": ("#3a86ff", "#1d4fa8"), "purple": ("#9b5de5", "#5f33a0"),
    "green": ("#2fb457", "#1b7336"), "yellow": ("#f9d71c", "#a38700"), "white": ("#f4f4f2", "#7a7a76"),
    "cyan": ("#1ec8e6", "#0f7f92"), "teal": ("#13a89e", "#0b6760"), "pink": ("#f15bb5", "#9e2d78"),
    "brown": ("#9a6324", "#5e3a12"), "grey": ("#a0a7b4", "#5b6270"), "lime": ("#a6e22e", "#5f8a10"),
    "lightblue": ("#8ecae6", "#3f7f9c"),
}


def esc(s):
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def fnum(v):
    return ("%.1f" % v).rstrip("0").rstrip(".")


class Board:
    def __init__(self, num, ox, oy, rails):
        self.num, self.ox, self.oy = num, ox, oy
        # rails: {"T1": ("+12V", "red"), ...}
        self.rails = rails

    def x(self, col):
        return self.ox + (col - 1) * P

    def y(self, row):
        return self.oy + ROW[row] * P

    def pt(self, col, row):
        if row in ("T1", "T2", "B1", "B2"):
            col = rail_col(col)
        return (self.x(col), self.y(row))


def rail_col(col):
    return col + 1 if col % 6 == 0 else col


def base_symbol():
    """The blank breadboard, drawn once and reused with <use>. Origin = hole (1, j)."""
    w = (COLS - 1) * P
    top, bot = ROW["T1"] * P - 20, ROW["B2"] * P + 20
    o = []
    o.append(f'<symbol id="bb" overflow="visible" viewBox="0 0 {fnum(w)} {fnum(bot - top)}">')
    o.append("</symbol>")
    # symbol viewBox tricks are awkward; use a <g> inside <defs> instead
    g = [f'<g id="bbbase">']
    g.append(f'<rect x="-18" y="{fnum(top)}" width="{fnum(w + 36)}" height="{fnum(bot - top)}" rx="7" '
             f'fill="#f5f3ed" stroke="#c9c3b1" stroke-width="1.5"/>')
    # centre channel
    yc0, yc1 = ROW["f"] * P + 7, ROW["e"] * P - 7
    g.append(f'<rect x="-10" y="{fnum(yc0)}" width="{fnum(w + 20)}" height="{fnum(yc1 - yc0)}" fill="#e4e0d3"/>')
    g.append(f'<line x1="-10" y1="{fnum(yc0)}" x2="{fnum(w + 10)}" y2="{fnum(yc0)}" stroke="#d3cdbb" stroke-width="1"/>')
    g.append(f'<line x1="-10" y1="{fnum(yc1)}" x2="{fnum(w + 10)}" y2="{fnum(yc1)}" stroke="#d3cdbb" stroke-width="1"/>')
    holes = []
    for col in range(1, COLS + 1):
        x = (col - 1) * P
        for r in "jihgfedcba":
            holes.append(f'M{fnum(x - 2.2)} {fnum(ROW[r] * P - 2.2)}h4.4v4.4h-4.4z')
    for r in ("T1", "T2", "B1", "B2"):
        for col in range(1, COLS + 1):
            if col % 6 == 0:
                continue
            x = (col - 1) * P
            holes.append(f'M{fnum(x - 2.2)} {fnum(ROW[r] * P - 2.2)}h4.4v4.4h-4.4z')
    g.append(f'<path d="{"".join(holes)}" fill="#4a4842"/>')
    # labels
    t = []
    for r in "jihgfedcba":
        t.append(f'<text x="-9" y="{fnum(ROW[r] * P + 2.5)}" text-anchor="middle">{r}</text>')
        t.append(f'<text x="{fnum(w + 9)}" y="{fnum(ROW[r] * P + 2.5)}" text-anchor="middle">{r}</text>')
    for col in [1] + list(range(5, COLS + 1, 5)):
        x = (col - 1) * P
        t.append(f'<text x="{fnum(x)}" y="{fnum(-1.0 * P + 2.3)}" text-anchor="middle">{col}</text>')
        t.append(f'<text x="{fnum(x)}" y="{fnum(12.0 * P + 2.3)}" text-anchor="middle">{col}</text>')
    g.append(f'<g font-size="6.5" fill="#8a8575" font-family="system-ui,Segoe UI,Arial,sans-serif">{"".join(t)}</g>')
    g.append("</g>")
    return "".join(g)


def board_svg(b, base_id="bbbase"):
    """Place the base breadboard and colour the rails."""
    o = [f'<g transform="translate({fnum(b.ox)} {fnum(b.oy)})"><use href="#{base_id}"/>']
    w = (COLS - 1) * P
    for r, (label, colour) in b.rails.items():
        y = ROW[r] * P
        fill, edge = COL[colour]
        o.append(f'<line x1="-6" y1="{fnum(y - 6.5)}" x2="{fnum(w + 6)}" y2="{fnum(y - 6.5)}" stroke="{fill}" stroke-width="1.6" opacity=".9"/>'
                 if r in ("T1", "B1") else
                 f'<line x1="-6" y1="{fnum(y + 6.5)}" x2="{fnum(w + 6)}" y2="{fnum(y + 6.5)}" stroke="{fill}" stroke-width="1.6" opacity=".9"/>')
        # label chips at both ends, outside the body
        for xx, anchor in ((-26, "end"), (w + 26, "start")):
            o.append(f'<text x="{fnum(xx)}" y="{fnum(y + 3)}" text-anchor="{anchor}" font-size="9" font-weight="700" '
                     f'fill="{edge}" font-family="system-ui,Segoe UI,Arial,sans-serif">{esc(label)}</text>')
    o.append(f'<text x="{fnum(w * 0.74)}" y="{fnum(ROW["T1"] * P - 24)}" text-anchor="middle" font-size="11" font-weight="700" '
             f'fill="#6b665a" font-family="system-ui,Segoe UI,Arial,sans-serif">BREADBOARD {b.num}</text>')
    o.append("</g>")
    return "".join(o)


# ------------------------------------------------------------------ wires
def _cubic(p0, c1, c2, p1, n=24):
    pts = []
    for i in range(n + 1):
        t = i / n
        a, b, c, d = (1 - t) ** 3, 3 * (1 - t) ** 2 * t, 3 * (1 - t) * t ** 2, t ** 3
        pts.append((a * p0[0] + b * c1[0] + c * c2[0] + d * p1[0], a * p0[1] + b * c1[1] + c * c2[1] + d * p1[1]))
    return pts


def wire_path(p0, p1, via=None, lift=None, up=None):
    """Return (svg path d, polyline) for a jumper wire."""
    if via:
        pts = [p0] + list(via) + [p1]
        d = f"M{fnum(pts[0][0])} {fnum(pts[0][1])}"
        poly = [pts[0]]
        for i in range(len(pts) - 1):
            a = pts[i - 1] if i > 0 else pts[i]
            b, c = pts[i], pts[i + 1]
            e = pts[i + 2] if i + 2 < len(pts) else pts[i + 1]
            c1 = (b[0] + (c[0] - a[0]) / 6, b[1] + (c[1] - a[1]) / 6)
            c2 = (c[0] - (e[0] - b[0]) / 6, c[1] - (e[1] - b[1]) / 6)
            d += f" C{fnum(c1[0])} {fnum(c1[1])} {fnum(c2[0])} {fnum(c2[1])} {fnum(c[0])} {fnum(c[1])}"
            poly += _cubic(b, c1, c2, c)[1:]
        return d, poly
    dist = math.hypot(p1[0] - p0[0], p1[1] - p0[1])
    if lift is None:
        lift = max(9.0, min(60.0, 0.2 * dist))
    sgn = -1 if (up is None or up) else 1
    c1 = (p0[0], p0[1] + sgn * lift)
    c2 = (p1[0], p1[1] + sgn * lift)
    d = (f"M{fnum(p0[0])} {fnum(p0[1])} C{fnum(c1[0])} {fnum(c1[1])} {fnum(c2[0])} {fnum(c2[1])} "
         f"{fnum(p1[0])} {fnum(p1[1])}")
    return d, _cubic(p0, c1, c2, p1)


def wire_svg(p0, p1, colour, num=None, via=None, lift=None, up=None, faint=False, ends=True, bt=0.5):
    fill, edge = COL[colour]
    d, poly = wire_path(p0, p1, via, lift, up)
    op = ' opacity=".22"' if faint else ""
    o = [f'<g{op}><path d="{d}" fill="none" stroke="{edge}" stroke-width="5.2" stroke-linecap="round"/>',
         f'<path d="{d}" fill="none" stroke="{fill}" stroke-width="3.4" stroke-linecap="round"/>']
    if ends:
        for p in (p0, p1):
            o.append(f'<circle cx="{fnum(p[0])}" cy="{fnum(p[1])}" r="3.1" fill="{edge}"/>'
                     f'<circle cx="{fnum(p[0])}" cy="{fnum(p[1])}" r="1.5" fill="#d9d9d4"/>')
    o.append("</g>")
    if num is not None and not faint:
        m = poly[min(len(poly) - 1, max(0, int(len(poly) * bt)))]
        o.append(badge(m[0], m[1], num))
    return "".join(o)


def badge(x, y, num):
    s = str(num)
    r = 7.2 if len(s) < 3 else 8.6
    return (f'<g><circle cx="{fnum(x)}" cy="{fnum(y)}" r="{r}" fill="#1b1f27" stroke="#fff" stroke-width="1.4"/>'
            f'<text x="{fnum(x)}" y="{fnum(y + 3)}" text-anchor="middle" font-size="8.5" font-weight="700" fill="#fff" '
            f'font-family="system-ui,Segoe UI,Arial,sans-serif">{s}</text></g>')


def flag_svg(p, colour, text, num=None, direction="up", length=26, faint=False):
    """A wire that leaves the board towards another breadboard: a stub with a vertical tag."""
    fill, edge = COL[colour]
    sgn = -1 if direction == "up" else 1
    q = (p[0], p[1] + sgn * length)
    op = ' opacity=".22"' if faint else ""
    o = [f'<g{op}><line x1="{fnum(p[0])}" y1="{fnum(p[1])}" x2="{fnum(q[0])}" y2="{fnum(q[1])}" stroke="{edge}" stroke-width="5.2" stroke-linecap="round"/>'
         f'<line x1="{fnum(p[0])}" y1="{fnum(p[1])}" x2="{fnum(q[0])}" y2="{fnum(q[1])}" stroke="{fill}" stroke-width="3.4" stroke-linecap="round"/>'
         f'<circle cx="{fnum(p[0])}" cy="{fnum(p[1])}" r="3.1" fill="{edge}"/><circle cx="{fnum(p[0])}" cy="{fnum(p[1])}" r="1.5" fill="#d9d9d4"/>']
    tl = 5.0 * len(text) + 8
    # vertical tag extending beyond the stub end
    if direction == "up":
        ty0, ty1 = q[1] - tl, q[1]
        tx = q[0]
        rot = f'rotate(-90 {fnum(tx)} {fnum(ty1 - 3)})'
        txt_x, txt_y = tx + 3, ty1 - 5
        o.append(f'<rect x="{fnum(tx - 6.5)}" y="{fnum(ty0)}" width="13" height="{fnum(tl)}" rx="3" fill="#fff" stroke="{edge}" stroke-width="1.3"/>')
        o.append(f'<text transform="translate({fnum(tx + 3)} {fnum(ty1 - 4)}) rotate(-90)" font-size="8" fill="#222" '
                 f'font-family="system-ui,Segoe UI,Arial,sans-serif">{esc(text)}</text>')
    else:
        ty0, ty1 = q[1], q[1] + tl
        tx = q[0]
        o.append(f'<rect x="{fnum(tx - 6.5)}" y="{fnum(ty0)}" width="13" height="{fnum(tl)}" rx="3" fill="#fff" stroke="{edge}" stroke-width="1.3"/>')
        o.append(f'<text transform="translate({fnum(tx + 3)} {fnum(ty0 + 4)}) rotate(90)" font-size="8" fill="#222" '
                 f'font-family="system-ui,Segoe UI,Arial,sans-serif">{esc(text)}</text>')
    o.append("</g>")
    if num is not None and not faint:
        o.append(badge(p[0], (p[1] + q[1]) / 2, num))
    return "".join(o)


# ------------------------------------------------------------------ parts
FONT = 'font-family="system-ui,Segoe UI,Arial,sans-serif"'
HALO = 'stroke="#fbfaf7" stroke-width="2.8" paint-order="stroke" stroke-linejoin="round"'


def glow(x, y, w, h, on):
    if not on:
        return ""
    return (f'<rect x="{fnum(x - 3)}" y="{fnum(y - 3)}" width="{fnum(w + 6)}" height="{fnum(h + 6)}" rx="6" fill="none" '
            f'stroke="#ff9f1c" stroke-width="2" stroke-dasharray="5 3"/>')


def header_row(b, col0, row, n, labels=None, label_side="in", used=None, rot_in=True):
    """Black pin-header strip with gold pins and small vertical labels."""
    o = []
    x0, x1, y = b.x(col0) - 7, b.x(col0 + n - 1) + 7, b.y(row)
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(y - 6)}" width="{fnum(x1 - x0)}" height="12" rx="1.5" fill="#26262a"/>')
    for i in range(n):
        o.append(f'<rect x="{fnum(b.x(col0 + i) - 2.4)}" y="{fnum(y - 2.4)}" width="4.8" height="4.8" fill="#e5c158"/>')
    if labels:
        for i in range(n):
            lab = labels.get(i + 1)
            if not lab:
                continue
            on = used is None or (i + 1) in used
            fill = "#ffffff" if on else "#8c96a6"
            cx = b.x(col0 + i)
            if label_side == "in-up":      # label sits above the row (module body is above)
                o.append(f'<text transform="translate({fnum(cx + 2.4)} {fnum(y - 9)}) rotate(-90)" font-size="6.8" fill="{fill}" {FONT}>{esc(lab)}</text>')
            else:                           # below the row
                o.append(f'<text transform="translate({fnum(cx + 2.4)} {fnum(y + 9)}) rotate(90)" font-size="6.8" fill="{fill}" {FONT}>{esc(lab)}</text>')
    return "".join(o)


ETH_H1 = {1: "VBUS", 2: "VSYS", 3: "GND", 4: "3V3_EN", 5: "3V3", 6: "GP21", 7: "GP17", 8: "GND", 9: "GP16", 10: "GP18",
          11: "CHIP_PU", 12: "GP15", 13: "GND", 14: "GP3", 15: "GP2", 16: "GP1", 17: "GP0", 18: "GND", 19: "GP44", 20: "GP43"}
ETH_H2 = {1: "GP20", 2: "GP19", 3: "GND", 4: "GP48", 5: "GP47", 6: "GP46", 7: "GP45", 8: "GND", 9: "GP42", 10: "GP41",
          11: "GP40", 12: "GP39", 13: "GND", 14: "GP38", 15: "GP37", 16: "GP36", 17: "GP35", 18: "GND", 19: "GP34", 20: "GP33"}


def draw_eth(b, c1, new=False):
    s = S
    ytop, ybot = b.y("h"), b.y("c")
    ymid = (ytop + ybot) / 2
    half = 10.5 * s
    x0 = b.x(c1) - 20 * s
    w = (48.26 + 4.5 + 20) * s
    o = [glow(x0, ymid - half, w, 2 * half, new)]
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(ymid - half)}" width="{fnum(w)}" height="{fnum(2 * half)}" rx="4" fill="#173b63" stroke="#0c2340" stroke-width="1.5"/>')
    # RJ45 and USB-C at the left (pin 1) end
    o.append(f'<rect x="{fnum(x0 - 6)}" y="{fnum(ymid - 8.5 * s)}" width="{fnum(17 * s)}" height="{fnum(15 * s)}" rx="2" fill="#c9ced6" stroke="#8b93a0"/>')
    o.append(f'<text x="{fnum(x0 + 2.5 * s)}" y="{fnum(ymid + 1)}" font-size="9" font-weight="700" fill="#39414f" {FONT}>RJ45</text>')
    o.append(f'<rect x="{fnum(x0 - 3)}" y="{fnum(ymid + 8.8 * s)}" width="{fnum(9.5 * s)}" height="{fnum(3.3 * s)}" rx="3" fill="#b8bec9" stroke="#8b93a0"/>')
    o.append(f'<text x="{fnum(x0 + 1.5 * s)}" y="{fnum(ymid + 12.3 * s + 8)}" font-size="7.5" font-weight="700" fill="#cfe3ff" {FONT}>USB-C</text>')
    # ESP32-S3 can
    o.append(f'<rect x="{fnum(x0 + 28 * s)}" y="{fnum(ymid - 8 * s)}" width="{fnum(18 * s)}" height="{fnum(16 * s)}" rx="2" fill="#aeb4bf" stroke="#7d8593"/>')
    o.append(f'<text x="{fnum(x0 + 37 * s)}" y="{fnum(ymid + 3)}" text-anchor="middle" font-size="8.5" font-weight="700" fill="#39414f" {FONT}>ESP32-S3</text>')
    o.append(f'<text x="{fnum(x0 + 58 * s)}" y="{fnum(ymid - 1)}" text-anchor="middle" font-size="8" fill="#9fc0e6" {FONT}>ESP32-S3-ETH</text>')
    o.append(f'<text x="{fnum(x0 + 58 * s)}" y="{fnum(ymid + 9)}" text-anchor="middle" font-size="7" fill="#9fc0e6" {FONT}>(Waveshare)</text>')
    o.append(header_row(b, c1, "h", 20, ETH_H1, "in-down", None))
    o.append(header_row(b, c1, "c", 20, ETH_H2, "in-up", None))
    # H1 labels sit below the top row (inside the body), H2 labels above the bottom row
    o.append(f'<text x="{fnum(b.x(c1) - 4)}" y="{fnum(ytop - 9)}" text-anchor="end" font-size="7" font-weight="700" fill="#b23a5a" {FONT}>pin 1</text>')
    o.append(f'<text x="{fnum(b.x(c1) - 4)}" y="{fnum(ybot + 14)}" text-anchor="end" font-size="7" font-weight="700" fill="#b23a5a" {FONT}>pin 1</text>')
    return "".join(o)


TMC_MODE = {1: "EN", 2: "MS1", 3: "MS2", 4: "PDN", 5: "PDN", 6: "CLK", 7: "STEP", 8: "DIR"}
TMC_MOTOR = {1: "VM", 2: "GND", 3: "A2", 4: "A1", 5: "B1", 6: "B2", 7: "VIO", 8: "GND"}


def draw_tmc(b, c1, new=False):
    s = S
    ytop, ybot = b.y("g"), b.y("c")
    x0, x1 = b.x(c1) - 1.6 * s, b.x(c1 + 7) + 1.6 * s
    y0, y1 = ytop - 1.4 * s, ybot + 1.4 * s
    o = [glow(x0, y0, x1 - x0, y1 - y0, new)]
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(y0)}" width="{fnum(x1 - x0)}" height="{fnum(y1 - y0)}" rx="3" fill="#20222a" stroke="#0b0c10" stroke-width="1.5"/>')
    o.append(f'<rect x="{fnum(x0 + 6)}" y="{fnum((y0 + y1) / 2 - 8)}" width="{fnum(26)}" height="{fnum(16)}" rx="2" fill="#aab1bd" stroke="#79818f"/>')
    o.append(f'<circle cx="{fnum(x1 - 14)}" cy="{fnum((y0 + y1) / 2)}" r="6" fill="#3a6cc6" stroke="#1d3f82"/>'
             f'<line x1="{fnum(x1 - 18)}" y1="{fnum((y0 + y1) / 2)}" x2="{fnum(x1 - 10)}" y2="{fnum((y0 + y1) / 2)}" stroke="#dfe8ff" stroke-width="1.4"/>')
    o.append(f'<text x="{fnum((x0 + x1) / 2 + 8)}" y="{fnum((y0 + y1) / 2 + 4)}" text-anchor="middle" font-size="10" font-weight="700" fill="#e8ebf2" {FONT}>TMC2209</text>')
    o.append(header_row(b, c1, "g", 8, TMC_MOTOR, "in-down", None))
    o.append(header_row(b, c1, "c", 8, TMC_MODE, "in-up", None))
    o.append(f'<text x="{fnum(x0 - 4)}" y="{fnum((y0 + y1) / 2 - 2)}" text-anchor="end" font-size="7.5" font-weight="700" fill="#b23a5a" {FONT}>EN / VM</text>'
             f'<text x="{fnum(x0 - 4)}" y="{fnum((y0 + y1) / 2 + 7)}" text-anchor="end" font-size="7.5" font-weight="700" fill="#b23a5a" {FONT}>end</text>')
    return "".join(o)


DEV_J1 = {1: "3V3", 2: "3V3", 3: "RST", 4: "GP4", 5: "GP5", 6: "GP6", 7: "GP7", 8: "GP15", 9: "GP16", 10: "GP17", 11: "GP18",
          12: "GP8", 13: "GP3", 14: "GP46", 15: "GP9", 16: "GP10", 17: "GP11", 18: "GP12", 19: "GP13", 20: "GP14", 21: "5V0", 22: "GND"}
DEV_J3 = {1: "GND", 2: "GP43 TX", 3: "GP44 RX", 4: "GP1", 5: "GP2", 6: "GP42", 7: "GP41", 8: "GP40", 9: "GP39", 10: "GP38",
          11: "GP37", 12: "GP36", 13: "GP35", 14: "GP0", 15: "GP45", 16: "GP48", 17: "GP47", 18: "GP21", 19: "GP20", 20: "GP19",
          21: "GND", 22: "GND"}


def draw_devkit(b, c1, new=False):
    s = S
    ytop, ybot = b.y("i"), b.y("b")
    ymid = (ytop + ybot) / 2
    half = 12.7 * s
    x0 = b.x(c1) - 2.0 * s
    w = (21 * 2.54 + 2 * 2.0 + 10) * s
    o = [glow(x0, ymid - half, w, 2 * half, new)]
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(ymid - half)}" width="{fnum(w)}" height="{fnum(2 * half)}" rx="4" fill="#1b1d22" stroke="#07080a" stroke-width="1.5"/>')
    o.append(f'<rect x="{fnum(x0 + 2 * s)}" y="{fnum(ymid - 9 * s)}" width="{fnum(18 * s)}" height="{fnum(18 * s)}" rx="2" fill="#aeb4bf" stroke="#7d8593"/>')
    o.append(f'<text x="{fnum(x0 + 11 * s)}" y="{fnum(ymid + 3)}" text-anchor="middle" font-size="8.5" font-weight="700" fill="#39414f" {FONT}>ESP32-S3</text>')
    for k, (yy, lab) in enumerate(((ymid - 4 * s, "USB (native)"), (ymid + 5 * s, "UART"))):
        o.append(f'<rect x="{fnum(x0 + w - 12 * s)}" y="{fnum(yy - 2 * s)}" width="{fnum(14 * s)}" height="{fnum(4.5 * s)}" rx="3" fill="#b8bec9" stroke="#8b93a0"/>')
        o.append(f'<text x="{fnum(x0 + w - 13 * s)}" y="{fnum(yy + 3)}" text-anchor="end" font-size="7.5" font-weight="700" fill="#cfd6e2" {FONT}>{lab}</text>')
    o.append(f'<text x="{fnum(x0 + 33 * s)}" y="{fnum(ymid + 3)}" text-anchor="middle" font-size="8.5" fill="#b8c0cf" {FONT}>ESP32-S3-DevKitC-1</text>')
    o.append(header_row(b, c1, "i", 22, DEV_J3, "in-down", None))
    o.append(header_row(b, c1, "b", 22, DEV_J1, "in-up", None))
    o.append(f'<text x="{fnum(b.x(c1) - 4)}" y="{fnum(ytop - 9)}" text-anchor="end" font-size="7" font-weight="700" fill="#b23a5a" {FONT}>J3 pin 1</text>')
    o.append(f'<text x="{fnum(b.x(c1) - 4)}" y="{fnum(ybot + 14)}" text-anchor="end" font-size="7" font-weight="700" fill="#b23a5a" {FONT}>J1 pin 1</text>')
    return "".join(o)


def draw_dip(b, c1, n, name, labels, new=False):
    """DIP-n in rows e (bottom, pins 1..n/2 left to right) and f (top, pins n..n/2+1)."""
    half = n // 2
    x0, x1 = b.x(c1) - 6, b.x(c1 + half - 1) + 6
    y0, y1 = b.y("f") - 5, b.y("e") + 5
    o = [glow(x0, y0, x1 - x0, y1 - y0, new)]
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(y0)}" width="{fnum(x1 - x0)}" height="{fnum(y1 - y0)}" rx="2.5" fill="#25262b" stroke="#0a0a0c" stroke-width="1.2"/>')
    o.append(f'<path d="M{fnum(x0)} {fnum((y0 + y1) / 2 - 5)} a5 5 0 0 1 0 10" fill="#f5f3ed"/>')
    o.append(f'<text x="{fnum((x0 + x1) / 2)}" y="{fnum((y0 + y1) / 2 + 3.2)}" text-anchor="middle" font-size="9" font-weight="700" fill="#e9ecf2" {FONT}>{esc(name)}</text>')
    for i in range(half):
        xb = b.x(c1 + i)
        o.append(f'<rect x="{fnum(xb - 2)}" y="{fnum(b.y("e") - 1)}" width="4" height="8" fill="#b9bcc4"/>')
        o.append(f'<rect x="{fnum(xb - 2)}" y="{fnum(b.y("f") - 7)}" width="4" height="8" fill="#b9bcc4"/>')
        lab = labels.get(i + 1)
        if lab:
            o.append(f'<text transform="translate({fnum(xb + 2.4)} {fnum(y1 - 3)}) rotate(-90)" font-size="6.4" fill="#cdd2dc" {FONT}>{esc(lab)}</text>')
        lab = labels.get(n - i)
        if lab:
            o.append(f'<text transform="translate({fnum(xb + 2.4)} {fnum(y0 + 3)}) rotate(90)" font-size="6.4" fill="#cdd2dc" {FONT}>{esc(lab)}</text>')
    o.append(f'<text x="{fnum(x0 - 3)}" y="{fnum(y1 + 8)}" text-anchor="end" font-size="7" font-weight="700" fill="#b23a5a" {FONT}>pin 1</text>')
    return "".join(o)


MCP_LABELS = {1: "GPB0", 2: "GPB1", 3: "GPB2", 4: "GPB3", 5: "GPB4", 6: "GPB5", 7: "GPB6", 8: "GPB7", 9: "VDD", 10: "VSS",
              11: "NC", 12: "SCL", 13: "SDA", 14: "NC", 15: "A0", 16: "A1", 17: "A2", 18: "RESET", 19: "INTB", 20: "INTA",
              21: "GPA0", 22: "GPA1", 23: "GPA2", 24: "GPA3", 25: "GPA4", 26: "GPA5", 27: "GPA6", 28: "GPA7"}
AHCT_LABELS = {1: "1OE", 2: "1A", 3: "1Y", 4: "2OE", 5: "2A", 6: "2Y", 7: "GND", 8: "3Y", 9: "3A", 10: "3OE", 11: "4Y",
               12: "4A", 13: "4OE", 14: "VCC"}


def draw_ky040(b, c1, title, new=False):
    """KY-040 module plugged into row j (pins GND + SW DT CLK, left to right), body hanging up/off the board."""
    s = S
    x_pin0 = b.x(c1)
    x0 = x_pin0 - 6.6 * s
    x1 = b.x(c1 + 4) + 2.2 * s
    y1 = b.y("j") + 2.3 * s
    y0 = y1 - 25 * s
    o = [glow(x0, y0, x1 - x0, y1 - y0, new)]
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(y0)}" width="{fnum(x1 - x0)}" height="{fnum(y1 - y0)}" rx="3" fill="#1f2025" stroke="#08080a" stroke-width="1.4"/>')
    cx, cy = (x0 + x1) / 2, y0 + 10 * s
    o.append(f'<rect x="{fnum(cx - 6.2 * s)}" y="{fnum(cy - 6.2 * s)}" width="{fnum(12.4 * s)}" height="{fnum(12.4 * s)}" rx="2" fill="#c3c7cf" stroke="#8a919d"/>')
    o.append(f'<circle cx="{fnum(cx)}" cy="{fnum(cy)}" r="{fnum(4.4 * s)}" fill="#8e95a1" stroke="#5f6672"/>')
    o.append(f'<circle cx="{fnum(cx)}" cy="{fnum(cy)}" r="{fnum(2.2 * s)}" fill="#d7dae0"/>')
    for hx in (x0 + 4 * s, x1 - 4 * s):
        o.append(f'<circle cx="{fnum(hx)}" cy="{fnum(y0 + 5 * s)}" r="{fnum(1.4 * s)}" fill="#f5f3ed"/>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(y0 + 17.6 * s)}" text-anchor="middle" font-size="9" font-weight="700" fill="#f3f3f3" {FONT}>{esc(title)}</text>')
    labs = ["GND", "+", "SW", "DT", "CLK"]
    for i, lab in enumerate(labs):
        o.append(f'<text x="{fnum(b.x(c1 + i))}" y="{fnum(y1 - 4.6 * s)}" text-anchor="middle" font-size="6.6" font-weight="700" fill="#f0f0f0" {FONT}>{lab}</text>')
        o.append(f'<rect x="{fnum(b.x(c1 + i) - 2.2)}" y="{fnum(b.y("j") - 2.2)}" width="4.4" height="4.4" fill="#e5c158"/>')
    return "".join(o)


def draw_button(b, c1, new=False):
    x0, x1 = b.x(c1) - 7, b.x(c1 + 2) + 7
    y0, y1 = b.y("f") - 5, b.y("e") + 5
    o = [glow(x0, y0, x1 - x0, y1 - y0, new)]
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(y0)}" width="{fnum(x1 - x0)}" height="{fnum(y1 - y0)}" rx="3" fill="#2a2b30" stroke="#0a0a0c"/>')
    o.append(f'<circle cx="{fnum((x0 + x1) / 2)}" cy="{fnum((y0 + y1) / 2)}" r="9" fill="#d8dce3" stroke="#9aa1ad"/>')
    for cx in (c1, c1 + 2):
        for r in ("e", "f"):
            o.append(f'<rect x="{fnum(b.x(cx) - 2.2)}" y="{fnum(b.y(r) - 2.2)}" width="4.4" height="4.4" fill="#e5c158"/>')
    o.append(f'<text x="{fnum((x0 + x1) / 2)}" y="{fnum(y0 - 4)}" text-anchor="middle" font-size="8" font-weight="700" fill="#555" {FONT}>TAP button</text>')
    return "".join(o)


BANDS = {"4.7k": ("#f2d11d", "#7b3fa0", "#d32f2f"), "1k": ("#8d5524", "#111", "#d32f2f"),
         "330": ("#f58b1f", "#f58b1f", "#8d5524"), "10k": ("#8d5524", "#111", "#f58b1f")}


def draw_resistor(p0, p1, value, label=None, new=False, dy=0, ldx=0, ldy=0):
    ang = math.degrees(math.atan2(p1[1] - p0[1], p1[0] - p0[0]))
    cx, cy = (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2
    L = math.hypot(p1[0] - p0[0], p1[1] - p0[1])
    bl = 34.0
    o = []
    if new:
        o.append(f'<g transform="translate({fnum(cx)} {fnum(cy)}) rotate({fnum(ang)})"><rect x="{fnum(-bl / 2 - 4)}" y="-10" width="{fnum(bl + 8)}" height="20" rx="6" fill="none" stroke="#ff9f1c" stroke-width="2" stroke-dasharray="5 3"/></g>')
    o.append(f'<g transform="translate({fnum(cx)} {fnum(cy)}) rotate({fnum(ang)})">')
    o.append(f'<line x1="{fnum(-L / 2)}" y1="0" x2="{fnum(L / 2)}" y2="0" stroke="#b9bcc4" stroke-width="2"/>')
    o.append(f'<rect x="{fnum(-bl / 2)}" y="-6" width="{fnum(bl)}" height="12" rx="5" fill="#e6d3a3" stroke="#a48b4a"/>')
    c = BANDS.get(value, ("#888", "#888", "#888"))
    for i, col in enumerate(c):
        o.append(f'<rect x="{fnum(-bl / 2 + 7 + i * 5.5)}" y="-6" width="3" height="12" fill="{col}"/>')
    o.append(f'<rect x="{fnum(bl / 2 - 8)}" y="-6" width="3" height="12" fill="#c9a227"/>')
    o.append("</g>")
    lab = label or value
    flip = -1 if ang in (90.0, -90.0) else 1
    tx, ty = cx + ldx, cy - 12 + dy + ldy
    o.append(f'<text x="{fnum(tx)}" y="{fnum(ty)}" text-anchor="middle" font-size="8" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{esc(lab)}</text>')
    return "".join(o)


def draw_cap_elec(p_plus, p_minus, label, new=False):
    cx = (p_plus[0] + p_minus[0]) / 2
    cy = (p_plus[1] + p_minus[1]) / 2 - 17
    r = 15
    o = []
    if new:
        o.append(f'<circle cx="{fnum(cx)}" cy="{fnum(cy)}" r="{r + 4}" fill="none" stroke="#ff9f1c" stroke-width="2" stroke-dasharray="5 3"/>')
    o.append(f'<line x1="{fnum(p_plus[0])}" y1="{fnum(p_plus[1])}" x2="{fnum(p_plus[0])}" y2="{fnum(cy)}" stroke="#b9bcc4" stroke-width="2"/>')
    o.append(f'<line x1="{fnum(p_minus[0])}" y1="{fnum(p_minus[1])}" x2="{fnum(p_minus[0])}" y2="{fnum(cy)}" stroke="#b9bcc4" stroke-width="2"/>')
    o.append(f'<circle cx="{fnum(cx)}" cy="{fnum(cy)}" r="{r}" fill="#23262e" stroke="#0a0b0e" stroke-width="1.2"/>')
    # white stripe on the minus side
    sx = p_minus[0] - cx
    o.append(f'<path d="M{fnum(cx + (4 if sx > 0 else -4) * 1)} {fnum(cy - 13)} A{r} {r} 0 0 {1 if sx > 0 else 0} {fnum(cx + (4 if sx > 0 else -4) * 1)} {fnum(cy + 13)} L{fnum(cx + (14 if sx > 0 else -14))} {fnum(cy)} Z" fill="#d6d9df" opacity=".9"/>')
    o.append(f'<text x="{fnum(cx + (9 if sx > 0 else -9))}" y="{fnum(cy + 3)}" text-anchor="middle" font-size="9" font-weight="700" fill="#23262e" {FONT}>−</text>')
    o.append(f'<text x="{fnum(cx + (-6 if sx > 0 else 6))}" y="{fnum(cy + 3)}" text-anchor="middle" font-size="9" font-weight="700" fill="#e9ecf2" {FONT}>+</text>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(cy - r - 4)}" text-anchor="middle" font-size="8" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{esc(label)}</text>')
    return "".join(o)


def draw_cap_ceramic(p0, p1, label="0.1µF", new=False):
    cx, cy = (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 - 8
    o = []
    if new:
        o.append(f'<rect x="{fnum(cx - 13)}" y="{fnum(cy - 12)}" width="26" height="24" rx="8" fill="none" stroke="#ff9f1c" stroke-width="2" stroke-dasharray="5 3"/>')
    o.append(f'<line x1="{fnum(p0[0])}" y1="{fnum(p0[1])}" x2="{fnum(p0[0])}" y2="{fnum(cy)}" stroke="#b9bcc4" stroke-width="1.8"/>'
             f'<line x1="{fnum(p1[0])}" y1="{fnum(p1[1])}" x2="{fnum(p1[0])}" y2="{fnum(cy)}" stroke="#b9bcc4" stroke-width="1.8"/>')
    o.append(f'<rect x="{fnum(cx - 9)}" y="{fnum(cy - 8)}" width="18" height="16" rx="6" fill="#f0a63a" stroke="#a96b16"/>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(cy + 3)}" text-anchor="middle" font-size="7.5" font-weight="700" fill="#5a3a08" {FONT}>104</text>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(cy - 12)}" text-anchor="middle" font-size="7.5" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{esc(label)}</text>')
    return "".join(o)


def draw_diode(p_anode, p_cath, label, new=False):
    ang = math.degrees(math.atan2(p_cath[1] - p_anode[1], p_cath[0] - p_anode[0]))
    cx, cy = (p_anode[0] + p_cath[0]) / 2, (p_anode[1] + p_cath[1]) / 2
    L = math.hypot(p_cath[0] - p_anode[0], p_cath[1] - p_anode[1])
    bl = min(40.0, L * 0.72)
    o = []
    if new:
        o.append(f'<g transform="translate({fnum(cx)} {fnum(cy)}) rotate({fnum(ang)})"><rect x="-26" y="-11" width="52" height="22" rx="6" fill="none" stroke="#ff9f1c" stroke-width="2" stroke-dasharray="5 3"/></g>')
    o.append(f'<g transform="translate({fnum(cx)} {fnum(cy)}) rotate({fnum(ang)})">'
             f'<line x1="{fnum(-L / 2)}" y1="0" x2="{fnum(L / 2)}" y2="0" stroke="#b9bcc4" stroke-width="2"/>'
             f'<rect x="{fnum(-bl / 2)}" y="-6.5" width="{fnum(bl)}" height="13" rx="3" fill="#25262b" stroke="#0a0a0c"/>'
             f'<rect x="{fnum(bl / 2 - 9)}" y="-6.5" width="6" height="13" fill="#dfe2e8"/></g>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(cy - 12)}" text-anchor="middle" font-size="8" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{esc(label)}</text>')
    return "".join(o)


def draw_to92(pts, label, new=False):
    """pts: three leg points, left to right (flat face towards you)."""
    cx = pts[1][0]
    cy = pts[1][1] - 18
    o = []
    if new:
        o.append(f'<rect x="{fnum(cx - 20)}" y="{fnum(cy - 17)}" width="40" height="34" rx="8" fill="none" stroke="#ff9f1c" stroke-width="2" stroke-dasharray="5 3"/>')
    for p in pts:
        o.append(f'<line x1="{fnum(p[0])}" y1="{fnum(p[1])}" x2="{fnum(p[0])}" y2="{fnum(cy + 4)}" stroke="#b9bcc4" stroke-width="1.8"/>')
    o.append(f'<path d="M{fnum(cx - 16)} {fnum(cy + 12)} L{fnum(cx - 16)} {fnum(cy - 2)} A16 16 0 0 1 {fnum(cx + 16)} {fnum(cy - 2)} L{fnum(cx + 16)} {fnum(cy + 12)} Z" fill="#25262b" stroke="#0a0a0c"/>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(cy + 6)}" text-anchor="middle" font-size="7" fill="#d9dce3" {FONT}>2N7000</text>')
    for p, lab in zip(pts, ("S", "G", "D")):
        o.append(f'<text x="{fnum(p[0])}" y="{fnum(p[1] + 12)}" text-anchor="middle" font-size="7.5" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{lab}</text>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(cy - 20)}" text-anchor="middle" font-size="8" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{esc(label)}</text>')
    return "".join(o)


def draw_header_pins(b, c1, row, n, labels, title, new=False):
    """A loose male pin header pushed into the breadboard (the fan's plug fits on it)."""
    x0, x1, y = b.x(c1) - 7, b.x(c1 + n - 1) + 7, b.y(row)
    o = [glow(x0, y - 22, x1 - x0, 28, new)]
    o.append(f'<rect x="{fnum(x0)}" y="{fnum(y - 6)}" width="{fnum(x1 - x0)}" height="12" rx="1.5" fill="#26262a"/>')
    for i in range(n):
        o.append(f'<rect x="{fnum(b.x(c1 + i) - 2.2)}" y="{fnum(y - 17)}" width="4.4" height="12" fill="#e5c158"/>')
        o.append(f'<text transform="translate({fnum(b.x(c1 + i) + 2.5)} {fnum(y - 21)}) rotate(-90)" font-size="7" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{labels[i]}</text>')
    o.append(f'<text x="{fnum((x0 + x1) / 2)}" y="{fnum(y - 52)}" text-anchor="middle" font-size="8" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{esc(title)}</text>')
    return "".join(o)


# ------------------------------------------------------------------ off-board objects
def draw_jack(x, y, new=False, label="12 V DC adapter"):
    """DC supply: barrel-jack screw-terminal adapter. (x, y) = top-left. Returns svg, + terminal, - terminal."""
    o = [glow(x, y, 70, 46, new)]
    o.append(f'<rect x="{fnum(x)}" y="{fnum(y)}" width="70" height="46" rx="4" fill="#2c3e50" stroke="#18232f" stroke-width="1.5"/>')
    o.append(f'<rect x="{fnum(x - 14)}" y="{fnum(y + 10)}" width="26" height="26" rx="3" fill="#15191f" stroke="#050607"/>'
             f'<circle cx="{fnum(x - 2)}" cy="{fnum(y + 23)}" r="7" fill="#0b0d10"/><circle cx="{fnum(x - 2)}" cy="{fnum(y + 23)}" r="2.4" fill="#8a919d"/>')
    for k, (lab, colr) in enumerate((("+", "#e63946"), ("−", "#9aa1ad"))):
        tx = x + 28 + k * 24
        o.append(f'<rect x="{fnum(tx - 9)}" y="{fnum(y + 26)}" width="18" height="16" rx="2" fill="#3da35d" stroke="#25663a"/>'
                 f'<circle cx="{fnum(tx)}" cy="{fnum(y + 34)}" r="5" fill="#cfd5dd" stroke="#8a919d"/>'
                 f'<text x="{fnum(tx)}" y="{fnum(y + 16)}" text-anchor="middle" font-size="11" font-weight="700" fill="{colr}" {FONT}>{lab}</text>')
    o.append(f'<text x="{fnum(x + 35)}" y="{fnum(y - 5)}" text-anchor="middle" font-size="8.5" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>{label}</text>')
    return "".join(o), (x + 28, y + 34), (x + 52, y + 34)


def draw_motor(cx, y, new=False):
    """NEMA17 stepper seen from the front, with its four wires ending at the bottom (y + 98)."""
    o = [glow(cx - 44, y, 88, 88, new)]
    o.append(f'<rect x="{fnum(cx - 42)}" y="{fnum(y)}" width="84" height="84" rx="6" fill="#4b5563" stroke="#1f2937" stroke-width="1.6"/>')
    for dx, dy in ((-32, 10), (32, 10), (-32, 74), (32, 74)):
        o.append(f'<circle cx="{fnum(cx + dx)}" cy="{fnum(y + dy)}" r="3.5" fill="#1f2937"/>')
    o.append(f'<circle cx="{fnum(cx)}" cy="{fnum(y + 42)}" r="24" fill="#6b7280" stroke="#1f2937"/><circle cx="{fnum(cx)}" cy="{fnum(y + 42)}" r="9" fill="#cfd5dd" stroke="#7c8594"/>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(y + 47)}" text-anchor="middle" font-size="9" font-weight="700" fill="#f3f4f6" {FONT}>NEMA17</text>')
    return "".join(o)


def draw_led_strip(x, y, new=False):
    """8-LED APA102 / SK9822 strip, four pads on the left. Returns svg and the +5V / CKI / DIN / GND pad positions."""
    o = [glow(x, y, 190, 46, new)]
    o.append(f'<rect x="{fnum(x)}" y="{fnum(y)}" width="190" height="46" rx="3" fill="#e9e6df" stroke="#a49f90"/>')
    for i in range(8):
        lx = x + 38 + i * 18
        o.append(f'<rect x="{fnum(lx)}" y="{fnum(y + 12)}" width="14" height="22" rx="2" fill="#f7f7f5" stroke="#b9b6ac"/>'
                 f'<circle cx="{fnum(lx + 7)}" cy="{fnum(y + 23)}" r="4" fill="#9ad1ff"/>')
    o.append(f'<text x="{fnum(x + 120)}" y="{fnum(y + 60)}" text-anchor="middle" font-size="8.5" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>8-LED APA102 / SK9822 strip</text>')
    pads = []
    for k, lab in enumerate(("+5V", "CKI", "DIN", "GND")):
        py = y + 6 + k * 11
        o.append(f'<circle cx="{fnum(x + 8)}" cy="{fnum(py + 2)}" r="3.6" fill="#e5c158" stroke="#a07d1d"/>'
                 f'<text x="{fnum(x + 16)}" y="{fnum(py + 5)}" font-size="7" font-weight="700" fill="#555" {FONT}>{lab}</text>')
        pads.append((x + 8, py + 2))
    return "".join(o), pads


def draw_fan(cx, y, new=False):
    o = [glow(cx - 50, y, 100, 100, new)]
    o.append(f'<rect x="{fnum(cx - 48)}" y="{fnum(y)}" width="96" height="96" rx="10" fill="#2f3338" stroke="#111"/>')
    o.append(f'<circle cx="{fnum(cx)}" cy="{fnum(y + 48)}" r="40" fill="#1b1d20" stroke="#4a4f57"/>')
    for k in range(7):
        a = math.radians(k * 360 / 7)
        o.append(f'<path d="M{fnum(cx)} {fnum(y + 48)} q{fnum(26 * math.cos(a) - 8 * math.sin(a))} {fnum(26 * math.sin(a) + 8 * math.cos(a))} {fnum(36 * math.cos(a + .5))} {fnum(36 * math.sin(a + .5))} z" fill="#3e444c"/>')
    o.append(f'<circle cx="{fnum(cx)}" cy="{fnum(y + 48)}" r="11" fill="#6b7280"/>')
    o.append(f'<text x="{fnum(cx)}" y="{fnum(y - 5)}" text-anchor="middle" font-size="8.5" font-weight="700" fill="#3b3b3b" {FONT} {HALO}>12 V 4-wire PWM fan (optional)</text>')
    return "".join(o)
