#!/usr/bin/env python3
"""
Render publication-grade visual artifacts for the Chenciner-Montgomery
3-body figure-eight exploration:

  1. fig8_kam_atlas.png — 2-panel MEGNO phase-space atlas (full soaring KAM
     continent + zoomed throat around the figure-eight and its unstable twin).
  2. fig8_geometry_and_bifurcations.svg — 2x2 vector dashboard:
     (A) Exact D3 Steiner deltoid mass-stability region at L=0,
     (B) 2,250x spin-stabilization explosion across L in [0, 0.40],
     (C) Real-space choreography vs. broken-choreography twin & 25%-asymmetric
         rotating rosette (m=(1,1,0.75)),
     (D) Montgomery's shape sphere S^2 showing the figure-eight dodging the
         3 equatorial binary collision poles and a chaotic slingshot escape.

Pure Python + Pillow (zero numpy/scipy dependency).
"""

from __future__ import annotations

import csv
import math
import struct
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

HERE = Path(__file__).resolve().parent

U0_EQ  = 0.347116888118927
W0_EQ  = 0.532724945388030
U_TWIN = 0.339407411990859
W_TWIN = 0.536184978151423
R_H8   = math.hypot(U0_EQ, W0_EQ)


def load_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
    candidates = (
        [
            "/usr/share/fonts/google-noto/NotoSans-Bold.ttf",
            "/usr/share/fonts/noto/NotoSans-Bold.ttf",
            "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf",
            "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        ]
        if bold
        else [
            "/usr/share/fonts/google-noto/NotoSans-Regular.ttf",
            "/usr/share/fonts/noto/NotoSans-Regular.ttf",
            "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
        ]
    )
    for p in candidates:
        if Path(p).exists():
            return ImageFont.truetype(p, size)
    return ImageFont.load_default()


def lerp_rgb(c1: tuple[int, int, int], c2: tuple[int, int, int], t: float) -> tuple[int, int, int]:
    t = max(0.0, min(1.0, t))
    return (
        int(round(c1[0] + (c2[0] - c1[0]) * t)),
        int(round(c1[1] + (c2[1] - c1[1]) * t)),
        int(round(c1[2] + (c2[2] - c1[2]) * t)),
    )


def megno_color(outcome: int, t_esc: float, megno: float, max_t: float) -> tuple[int, int, int]:
    if outcome == 0:
        if megno < 1.85:
            t = max(0.0, min(1.0, megno / 1.85))
            return lerp_rgb((255, 245, 200), (245, 178, 52), t)
        if megno <= 2.35:
            if megno <= 2.02:
                t = (megno - 1.85) / 0.17
                return lerp_rgb((118, 232, 245), (28, 128, 210), t)
            t = (megno - 2.02) / 0.33
            return lerp_rgb((28, 128, 210), (16, 62, 138), t)
        t = min(1.0, math.log1p(megno - 2.35) / math.log1p(47.65))
        if t < 0.45:
            return lerp_rgb((255, 126, 78), (218, 52, 108), t / 0.45)
        return lerp_rgb((218, 52, 108), (112, 34, 118), (t - 0.45) / 0.55)

    s = min(1.0, math.log1p(max(0.0, t_esc)) / math.log1p(max_t))
    base = lerp_rgb((9, 12, 20), (54, 46, 86), s ** 1.15)
    if outcome == 1:
        return lerp_rgb(base, (34, 102, 128), 0.32 * s)
    if outcome == 2:
        return lerp_rgb(base, (124, 96, 38), 0.32 * s)
    if outcome == 3:
        return lerp_rgb(base, (124, 46, 88), 0.32 * s)
    return base


def render_megno_panel(bin_path: Path, max_t: float) -> tuple[Image.Image, tuple[float, float, float, float]]:
    raw = bin_path.read_bytes()
    W, H = struct.unpack_from("<ii", raw, 0)
    u0, u1, w0, w1 = struct.unpack_from("<4d", raw, 8)
    off = 40
    img = Image.new("RGB", (W, H))
    px = bytearray(W * H * 3)
    idx = 0
    for k in range(W * H):
        out, t_esc, meg = struct.unpack_from("<B3xff", raw, off + k * 12)
        r, g, b = megno_color(out, t_esc, meg, max_t)
        px[idx] = r
        px[idx + 1] = g
        px[idx + 2] = b
        idx += 3
    img.frombytes(bytes(px))
    return img, (u0, u1, w0, w1)


def draw_dashed_polyline(
    draw: ImageDraw.ImageDraw,
    pts: list[tuple[float, float]],
    fill: tuple[int, int, int],
    width: int = 2,
    dash: float = 8.0,
    gap: float = 6.0,
) -> None:
    if len(pts) < 2:
        return
    drawing = True
    rem = dash
    for i in range(len(pts) - 1):
        x0, y0 = pts[i]
        x1, y1 = pts[i + 1]
        seg = math.hypot(x1 - x0, y1 - y0)
        if seg < 1e-9:
            continue
        ux, uy = (x1 - x0) / seg, (y1 - y0) / seg
        pos = 0.0
        while pos < seg - 1e-9:
            step = min(rem, seg - pos)
            if drawing:
                draw.line(
                    [(x0 + ux * pos, y0 + uy * pos), (x0 + ux * (pos + step), y0 + uy * (pos + step))],
                    fill=fill,
                    width=width,
                )
            pos += step
            rem -= step
            if rem <= 1e-9:
                drawing = not drawing
                rem = dash if drawing else gap


def build_kam_atlas_png() -> None:
    wing_img, (wu0, wu1, ww0, ww1) = render_megno_panel(HERE / "atlas_wing.bin", 60.0)
    thrt_img, (tu0, tu1, tw0, tw1) = render_megno_panel(HERE / "atlas_throat.bin", 100.0)

    PW, PH = 1000, 440
    wing_panel = wing_img.resize((PW, PH), Image.Resampling.BICUBIC)
    thrt_panel = thrt_img.resize((PW, PH), Image.Resampling.BICUBIC)

    CW, CH = 1140, 1140
    canvas = Image.new("RGB", (CW, CH), (11, 14, 21))
    draw = ImageDraw.Draw(canvas)

    f_title = load_font(22, bold=True)
    f_sub = load_font(13, bold=False)
    f_pt = load_font(15, bold=True)
    f_lbl = load_font(12, bold=False)
    f_sm = load_font(11, bold=False)

    draw.text((78, 18), "Why the Figure-Eight Survives: MEGNO Phase-Space Atlas (L = 0)", fill=(238, 244, 255), font=f_title)
    draw.text(
        (78, 47),
        "Equal-mass Euler collinear velocity slice r1=(1,0), r2=(-1,0), r3=(0,0), v1=v2=(u,w), v3=(-2u,-2w)  |  DOPRI5 variational MEGNO",
        fill=(148, 162, 186),
        font=f_sub,
    )

    panels = [
        ("A. Full Soaring KAM Continent  (60 periods, 1000x480 orbits)", wing_panel, (wu0, wu1, ww0, ww1), (78, 96), True),
        ("B. Zoom into the Narrow Throat & Broken-Choreography Twin  (100 periods, 840x400 orbits)", thrt_panel, (tu0, tu1, tw0, tw1), (78, 600), False),
    ]

    for title, pimg, (u0, u1, w0, w1), (ox, oy), is_wide in panels:
        draw.text((ox, oy - 24), title, fill=(224, 232, 246), font=f_pt)
        canvas.paste(pimg, (ox, oy))
        draw.rectangle([ox - 1, oy - 1, ox + PW, oy + PH], outline=(58, 70, 96), width=1)

        def to_px(u: float, w: float) -> tuple[float, float]:
            return (
                ox + (u - u0) / (u1 - u0) * (PW - 1),
                oy + (w1 - w) / (w1 - w0) * (PH - 1),
            )

        arc_pts = []
        for k in range(300):
            u = u0 + (u1 - u0) * k / 299.0
            rem = R_H8 * R_H8 - u * u
            if rem <= 0:
                continue
            w = math.sqrt(rem)
            if w0 <= w <= w1:
                arc_pts.append(to_px(u, w))
        draw_dashed_polyline(draw, arc_pts, fill=(226, 234, 248), width=2, dash=7.0, gap=5.0)
        if arc_pts:
            lx, ly = arc_pts[int(len(arc_pts) * (0.14 if is_wide else 0.78))]
            draw.text((lx + 8, ly - 16), "H = H8 (fixed energy)", fill=(232, 240, 252), font=f_sm)

        if is_wide:
            bx0, by0 = to_px(tu0, tw1)
            bx1, by1 = to_px(tu1, tw0)
            box_pts = [(bx0, by0), (bx1, by0), (bx1, by1), (bx0, by1), (bx0, by0)]
            draw_dashed_polyline(draw, box_pts, fill=(255, 224, 130), width=2, dash=6.0, gap=4.0)
            draw.text((bx1 + 6, by0 - 4), "Panel B zoom", fill=(255, 224, 130), font=f_sm)

        fx, fy = to_px(U0_EQ, W0_EQ)
        tx, ty = to_px(U_TWIN, W_TWIN)

        r = 7
        draw.ellipse([fx - r, fy - r, fx + r, fy + r], outline=(255, 255, 255), width=2)
        draw.line([(fx - 12, fy), (fx - 4, fy)], fill=(255, 255, 255), width=2)
        draw.line([(fx + 4, fy), (fx + 12, fy)], fill=(255, 255, 255), width=2)
        draw.line([(fx, fy - 12), (fx, fy - 4)], fill=(255, 255, 255), width=2)
        draw.line([(fx, fy + 4), (fx, fy + 12)], fill=(255, 255, 255), width=2)

        d = 6
        draw.polygon([(tx, ty - d), (tx + d, ty), (tx, ty + d), (tx - d, ty)], fill=(255, 96, 82), outline=(255, 255, 255))

        if is_wide:
            draw.rectangle([fx + 12, fy + 12, fx + 158, fy + 31], fill=(11, 14, 21), outline=(92, 112, 145), width=1)
            draw.text((fx + 17, fy + 14), "Figure-8 (tau1=1.9972)", fill=(255, 255, 255), font=f_sm)
            draw.rectangle([tx - 184, ty - 34, tx - 10, ty - 15], fill=(11, 14, 21), outline=(215, 102, 92), width=1)
            draw.text((tx - 178, ty - 31), "Unstable twin (tau1=2.0084)", fill=(255, 166, 150), font=f_sm)
        else:
            draw.line([(fx + 9, fy + 8), (fx + 45, fy + 38)], fill=(255, 255, 255), width=1)
            draw.rectangle([fx + 45, fy + 28, fx + 275, fy + 64], fill=(12, 16, 26), outline=(140, 170, 210), width=1)
            draw.text((fx + 53, fy + 32), "Stable Figure-Eight (choreography)", fill=(255, 255, 255), font=f_sm)
            draw.text((fx + 53, fy + 47), "u=0.34712, w=0.53272 | tau1=+1.9972", fill=(140, 224, 245), font=f_sm)

            draw.line([(tx - 8, ty - 8), (tx - 45, ty - 42)], fill=(255, 132, 118), width=1)
            draw.rectangle([tx - 310, ty - 74, tx - 45, ty - 36], fill=(12, 16, 26), outline=(240, 110, 96), width=1)
            draw.text((tx - 302, ty - 70), "Unstable Broken-Choreography Twin", fill=(255, 168, 152), font=f_sm)
            draw.text((tx - 302, ty - 54), "u=0.33941, w=0.53618 | tau1=+2.0084", fill=(230, 195, 190), font=f_sm)

        nx = 7 if is_wide else 9
        for k in range(nx):
            val = u0 + (u1 - u0) * k / (nx - 1)
            x = ox + PW * k / (nx - 1)
            draw.line([(x, oy + PH), (x, oy + PH + 5)], fill=(120, 134, 160), width=1)
            lbl = f"{val:.2f}" if is_wide else f"{val:.3f}"
            draw.text((x - 16, oy + PH + 8), lbl, fill=(168, 180, 202), font=f_sm)
        ny = 5
        for k in range(ny):
            val = w0 + (w1 - w0) * k / (ny - 1)
            y = oy + PH - PH * k / (ny - 1)
            draw.line([(ox - 5, y), (ox, y)], fill=(120, 134, 160), width=1)
            lbl = f"{val:.2f}" if is_wide else f"{val:.3f}"
            draw.text((ox - 46, y - 6), lbl, fill=(168, 180, 202), font=f_sm)
        draw.text((ox + PW // 2 - 90, oy + PH + 25), "u (parallel Euler velocity)", fill=(184, 196, 218), font=f_lbl)
        draw.text((10, oy + PH // 2 - 12), "w", fill=(184, 196, 218), font=f_pt)

    ly = 1084
    lx0, lw, lh = 78, 520, 16
    for i in range(lw):
        t = i / (lw - 1)
        if t < 0.20:
            col = megno_color(0, 100.0, 1.85 * (t / 0.20), 100.0)
        elif t < 0.50:
            col = megno_color(0, 100.0, 1.85 + 0.50 * ((t - 0.20) / 0.30), 100.0)
        elif t < 0.78:
            u = (t - 0.50) / 0.28
            col = megno_color(0, 100.0, 2.35 + (math.exp(u * math.log1p(47.65)) - 1.0), 100.0)
        else:
            u = 1.0 - (t - 0.78) / 0.22
            col = megno_color(1, (math.exp(u * math.log1p(100.0)) - 1.0), 50.0, 100.0)
        draw.line([(lx0 + i, ly), (lx0 + i, ly + lh)], fill=col, width=1)
    draw.rectangle([lx0 - 1, ly - 1, lx0 + lw, ly + lh], outline=(72, 84, 110), width=1)
    draw.text((lx0, ly + 21), "Resonant core (Y<1.8)", fill=(245, 200, 100), font=f_sm)
    draw.text((lx0 + 148, ly + 21), "KAM torus (Y~2.0)", fill=(108, 212, 238), font=f_sm)
    draw.text((lx0 + 278, ly + 21), "Chaotic web (Y>3)", fill=(245, 118, 128), font=f_sm)
    draw.text((lx0 + 414, ly + 21), "Hyperbolic escape", fill=(154, 162, 192), font=f_sm)

    draw.text((lx0 + lw + 30, ly - 2), "At fixed energy H = H8 (dashed arc), the unstable twin", fill=(182, 194, 214), font=f_sm)
    draw.text((lx0 + lw + 30, ly + 15), "pinches the KAM waist down to |dv| ~ 0.008.", fill=(182, 194, 214), font=f_sm)

    out_path = HERE / "fig8_kam_atlas.png"
    canvas.save(out_path, optimize=True)
    print(f"Wrote {out_path} ({CW}x{CH})")


def build_geometry_and_bifurcations_svg() -> None:
    del_rows = list(csv.DictReader((HERE / "mass_deltoid_boundary.csv").open()))
    rot_rows = list(csv.DictReader((HERE / "rotating_mass_window.csv").open()))

    trajs: dict[str, list[dict[str, float]]] = {}
    with (HERE / "trajectories.csv").open() as f:
        for row in csv.DictReader(f):
            lbl = row["label"]
            trajs.setdefault(lbl, []).append({k: float(v) for k, v in row.items() if k != "label"})

    svg: list[str] = []
    W, H = 1000, 860
    svg.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}">')
    svg.append('<rect width="100%" height="100%" fill="#0b0e15"/>')
    svg.append(
        "<style>"
        'text { font-family: "Noto Sans", "DejaVu Sans", sans-serif; }'
        ".hdr { fill: #eef4ff; font-size: 18px; font-weight: 700; }"
        ".hsub { fill: #93a3be; font-size: 11.5px; }"
        ".pt { fill: #e6eefc; font-size: 13.5px; font-weight: 700; }"
        ".ps { fill: #8c9bb6; font-size: 10px; }"
        ".lbl { fill: #a6b4cc; font-size: 10px; }"
        ".lblb { fill: #dce6f7; font-size: 10px; font-weight: 600; }"
        ".ax { stroke: #36425a; stroke-width: 1; }"
        ".gr { stroke: #1a2132; stroke-width: 1; }"
        ".card { fill: #0f1420; stroke: #222c42; stroke-width: 1; rx: 8; }"
        "</style>"
    )

    svg.append('<text x="24" y="30" class="hdr">Symmetry, Catastrophe Geometry &amp; Spin Stabilization of the Figure-Eight</text>')
    svg.append(
        '<text x="24" y="48" class="hsub">'
        "Exact s=6 order-12 Gauss-Legendre monodromy &amp; DOPRI5 nonlinear dynamics (m1+m2+m3=3, G=1)"
        "</text>"
    )

    for cx, cy, cw, ch in [(20, 62, 470, 382), (510, 62, 470, 382), (20, 462, 470, 382), (510, 462, 470, 382)]:
        svg.append(f'<rect x="{cx}" y="{cy}" width="{cw}" height="{ch}" class="card"/>')

    # =========================================================================
    # PANEL A: Exact D3 Mass-Simplex Stability Deltoid at L = 0
    # =========================================================================
    ax_cx, ax_cy = 255.0, 260.0
    scale_a = 1.48e6  # 8.06e-5 -> ~119 px
    svg.append('<text x="36" y="86" class="pt">A. L = 0 Mass-Simplex Stability Deltoid</text>')
    svg.append('<text x="36" y="102" class="ps">360-ray 3-body boundary vs. exact Steiner deltoid (ratio 2.9999 : 1)</text>')

    r_edge = 2.68666913e-5
    pr_fold = r_edge * scale_a
    pr_cusp = 3.0 * r_edge * scale_a
    svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy:.1f}" r="{pr_fold:.1f}" fill="none" stroke="#1e2840" stroke-dasharray="3,4"/>')
    svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy:.1f}" r="{pr_cusp:.1f}" fill="none" stroke="#1e2840" stroke-dasharray="3,4"/>')
    svg.append(f'<text x="{ax_cx + pr_fold + 8:.1f}" y="{ax_cy + 18:.1f}" class="ps">r_fold = 2.69e-5</text>')
    svg.append(f'<text x="{ax_cx + pr_cusp * 0.68:.1f}" y="{ax_cy - pr_cusp * 0.78:.1f}" class="ps">r_cusp = 8.06e-5</text>')

    for deg, label in [(90, "+m3 (fold)"), (270, "-m3 (cusp)"), (210, "+m2"), (30, "-m2"), (330, "+m1"), (150, "-m1")]:
        rad_a = math.radians(deg)
        x2 = ax_cx + 128.0 * math.cos(rad_a)
        y2 = ax_cy - 128.0 * math.sin(rad_a)
        svg.append(f'<line x1="{ax_cx:.1f}" y1="{ax_cy:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke="#232e47" stroke-width="1"/>')
        lx = ax_cx + 135.0 * math.cos(rad_a)
        ly = ax_cy - 135.0 * math.sin(rad_a) + (4 if deg != 270 else 9)
        anc = "middle" if deg in (90, 270) else ("start" if math.cos(rad_a) > 0 else "end")
        svg.append(f'<text x="{lx:.1f}" y="{ly:.1f}" text-anchor="{anc}" class="lbl">{label}</text>')

    pts_comp = [f"{ax_cx + float(r['s1']) * scale_a:.2f},{ax_cy - float(r['s2']) * scale_a:.2f}" for r in del_rows]
    svg.append(f'<polygon points="{" ".join(pts_comp)}" fill="#1b7ea8" fill-opacity="0.30" stroke="#38d4f0" stroke-width="2.2"/>')

    pts_st = []
    for j in range(361):
        t = 2.0 * math.pi * j / 360.0
        ds1 = r_edge * (2.0 * math.sin(t) - math.sin(2.0 * t))
        ds2 = -r_edge * (2.0 * math.cos(t) + math.cos(2.0 * t))
        pts_st.append(f"{ax_cx + ds1 * scale_a:.2f},{ax_cy - ds2 * scale_a:.2f}")
    svg.append(f'<polyline points="{" ".join(pts_st)}" fill="none" stroke="#ffd166" stroke-width="1.4" stroke-dasharray="5,4"/>')

    svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy:.1f}" r="3.5" fill="#ffffff"/>')
    svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy - pr_fold:.1f}" r="4" fill="#ff6b6b" stroke="#fff" stroke-width="1"/>')
    svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy + pr_cusp:.1f}" r="4" fill="#ffd166" stroke="#fff" stroke-width="1"/>')

    svg.append('<line x1="36" y1="418" x2="56" y2="418" stroke="#38d4f0" stroke-width="2.2"/>')
    svg.append('<text x="62" y="422" class="lbl">Exact 3-body boundary</text>')
    svg.append('<line x1="36" y1="433" x2="56" y2="433" stroke="#ffd166" stroke-width="1.5" stroke-dasharray="5,4"/>')
    svg.append('<text x="62" y="437" class="lbl">Analytical Steiner deltoid</text>')
    svg.append('<text x="476" y="437" text-anchor="end" class="lblb">dtheta = 0 identically (R_phi T/2 sym.)</text>')

    # =========================================================================
    # PANEL B: Spin Stabilization — Mass Window vs Angular Momentum L
    # =========================================================================
    bx0, bx1, by0, by1 = 568.0, 962.0, 134.0, 396.0
    svg.append('<text x="526" y="86" class="pt">B. Spin Stabilization: 2,250x Wider Mass Window</text>')
    svg.append('<text x="526" y="102" class="ps">Linearly stable m3 = 1 + delta (m1=m2=1) vs. angular momentum L_iso</text>')

    # Non-overlapping legend strip right above Panel B plot box
    for lx, txt, col in [
        (568, "Fold / Pitchfork (tau1=+2)", "#ffd166"),
        (718, "Krein collision", "#c084fc"),
        (816, "Period-doubling (tau2=-2)", "#4ade80"),
    ]:
        svg.append(f'<circle cx="{lx}" cy="119" r="3.2" fill="{col}"/>')
        svg.append(f'<text x="{lx + 6}" y="122.5" class="ps">{txt}</text>')

    def b_xy(L: float, delta_pct: float) -> tuple[float, float]:
        x = bx0 + (L / 0.41) * (bx1 - bx0)
        y = by1 - ((delta_pct - (-32.0)) / 52.0) * (by1 - by0)
        return x, y

    for dp in [-30, -20, -10, 0, 10, 20]:
        _, gy = b_xy(0.0, dp)
        cls = "ax" if dp == 0 else "gr"
        svg.append(f'<line x1="{bx0:.1f}" y1="{gy:.1f}" x2="{bx1:.1f}" y2="{gy:.1f}" class="{cls}"/>')
        svg.append(f'<text x="{bx0 - 8:.1f}" y="{gy + 3.5:.1f}" text-anchor="end" class="lbl">{dp:+d}%</text>')
    for Lv in [0.0, 0.1, 0.2, 0.3, 0.4]:
        gx, _ = b_xy(Lv, 0.0)
        svg.append(f'<line x1="{gx:.1f}" y1="{by0:.1f}" x2="{gx:.1f}" y2="{by1:.1f}" class="gr"/>')
        svg.append(f'<text x="{gx:.1f}" y="{by1 + 15:.1f}" text-anchor="middle" class="lbl">{Lv:.1f}</text>')
    svg.append(f'<text x="{0.5*(bx0+bx1):.1f}" y="{by1 + 32:.1f}" text-anchor="middle" class="lbl">Angular momentum L_iso (r1_iso = 1)</text>')
    svg.append(f'<text x="524" y="{0.5*(by0+by1):.1f}" transform="rotate(-90 524 {0.5*(by0+by1):.1f})" text-anchor="middle" class="lbl">m3 - 1 (%)</text>')

    env_L = [0.0] + [float(r["L_iso"]) for r in rot_rows] + [0.3995]
    env_hi = [0.00403] + [100.0 * float(r["delta_max"]) for r in rot_rows] + [0.0]
    env_lo = [-0.01209] + [100.0 * float(r["delta_min"]) for r in rot_rows] + [0.0]

    poly_pts = [f"{b_xy(L, h)[0]:.1f},{b_xy(L, h)[1]:.1f}" for L, h in zip(env_L, env_hi)] + [
        f"{b_xy(L, l)[0]:.1f},{b_xy(L, l)[1]:.1f}" for L, l in zip(reversed(env_L), reversed(env_lo))
    ]
    svg.append(f'<polygon points="{" ".join(poly_pts)}" fill="#20a4b8" fill-opacity="0.28" stroke="#38d4f0" stroke-width="2"/>')

    b_colors = {"tau1>+2": "#ffd166", "fold": "#ff6b6b", "KREIN": "#c084fc", "tau2<-2": "#4ade80"}
    for r in rot_rows:
        Lv = float(r["L_iso"])
        for val_k, rsn_k in [("delta_max", "reason_max"), ("delta_min", "reason_min")]:
            px, py = b_xy(Lv, 100.0 * float(r[val_k]))
            col = b_colors.get(r[rsn_k], "#ffffff")
            svg.append(f'<circle cx="{px:.1f}" cy="{py:.1f}" r="3.3" fill="{col}" stroke="#0b0e15" stroke-width="0.8"/>')

    sx_v, sy_v = b_xy(0.15, -25.0)
    svg.append(f'<circle cx="{sx_v:.1f}" cy="{sy_v:.1f}" r="5.2" fill="#ffd166" stroke="#ffffff" stroke-width="1.5"/>')
    svg.append(f'<text x="{sx_v + 9:.1f}" y="{sy_v + 4:.1f}" class="lblb">m3=0.75 (1,000 orbits OK!)</text>')

    x0_l, y0_l = b_xy(0.0, 0.0)
    svg.append(f'<circle cx="{x0_l:.1f}" cy="{y0_l:.1f}" r="4" fill="#ff6b6b" stroke="#fff" stroke-width="1"/>')
    svg.append(f'<text x="{x0_l + 8:.1f}" y="{y0_l - 22:.1f}" class="lbl">L=0: 0.016%</text>')
    svg.append(f'<line x1="{x0_l + 2:.1f}" y1="{y0_l - 4:.1f}" x2="{x0_l + 18:.1f}" y2="{y0_l - 18:.1f}" stroke="#ff6b6b" stroke-width="1"/>')

    xj, yj = b_xy(0.115, -16.5)
    svg.append(f'<text x="{xj - 6:.1f}" y="{yj:.1f}" text-anchor="end" class="ps" fill="#7be0f5">L~0.115</text>')
    svg.append(f'<text x="{xj - 6:.1f}" y="{yj + 12:.1f}" text-anchor="end" class="ps" fill="#7be0f5">tau1&lt;2 jump</text>')

    xc, _ = b_xy(0.3995, 0.0)
    svg.append(f'<line x1="{xc:.1f}" y1="{by0:.1f}" x2="{xc:.1f}" y2="{by1:.1f}" stroke="#4ade80" stroke-dasharray="3,4" stroke-width="1.2"/>')
    svg.append(f'<text x="{xc - 6:.1f}" y="{by1 - 44:.1f}" text-anchor="end" class="lbl" fill="#4ade80">L_crit=0.3995</text>')
    svg.append(f'<text x="{xc - 6:.1f}" y="{by1 - 31:.1f}" text-anchor="end" class="ps" fill="#4ade80">(tau2=-2)</text>')

    # =========================================================================
    # PANEL C: Real-Space Orbits
    # =========================================================================
    svg.append('<text x="36" y="486" class="pt">C. Choreography vs. Broken Twin &amp; Rotating Asymmetric Triple</text>')
    svg.append('<text x="36" y="502" class="ps">Left: L=0 equal-mass figure-8 (gold) vs. unstable twin (coral)  |  Right: m=(1,1,0.75), L=0.15</text>')

    c1x, c1y, c1s = 143.0, 666.0, 82.0
    ca, sa = math.cos(-0.24552), math.sin(-0.24552)

    def rot_pt(x: float, y: float) -> tuple[float, float]:
        return ca * x - sa * y, sa * x + ca * y

    for bidx, col, dash in [(1, "#ff7864", "3,3"), (2, "#ff7864", "3,3"), (3, "#ff4d6d", "4,2")]:
        pts = [f"{c1x + rot_pt(p[f'x{bidx}'], p[f'y{bidx}'])[0] * c1s:.1f},{c1y - rot_pt(p[f'x{bidx}'], p[f'y{bidx}'])[1] * c1s:.1f}" for p in trajs["twin"][::4]]
        svg.append(f'<polyline points="{" ".join(pts)}" fill="none" stroke="{col}" stroke-width="1.3" stroke-dasharray="{dash}" opacity="0.85"/>')

    pts_st8 = [f"{c1x + rot_pt(p['x1'], p['y1'])[0] * c1s:.1f},{c1y - rot_pt(p['x1'], p['y1'])[1] * c1s:.1f}" for p in trajs["stable"][::3]]
    svg.append(f'<polyline points="{" ".join(pts_st8)}" fill="none" stroke="#ffd166" stroke-width="2.4"/>')
    p0 = trajs["stable"][0]
    for bidx, col in [(1, "#38d4f0"), (2, "#38d4f0"), (3, "#ffd166")]:
        rx, ry = rot_pt(p0[f"x{bidx}"], p0[f"y{bidx}"])
        svg.append(f'<circle cx="{c1x + rx * c1s:.1f}" cy="{c1y - ry * c1s:.1f}" r="4.2" fill="{col}" stroke="#0b0e15" stroke-width="1"/>')
    svg.append('<text x="143" y="810" text-anchor="middle" class="lbl">L=0: Equal-mass choreography</text>')
    svg.append('<text x="143" y="824" text-anchor="middle" class="ps">Twin splits body 3 off shared loop</text>')

    svg.append('<line x1="258" y1="520" x2="258" y2="830" stroke="#1e273c" stroke-width="1"/>')

    c2x, c2y, c2s = 374.0, 666.0, 73.0
    for bidx, col, op, sw in [(1, "#38d4f0", 0.55, 1.0), (2, "#5b8def", 0.55, 1.0), (3, "#ffd166", 0.90, 1.3)]:
        pts = [f"{c2x + p[f'x{bidx}'] * c2s:.1f},{c2y - p[f'y{bidx}'] * c2s:.1f}" for p in trajs["rot_asym"][::3]]
        svg.append(f'<polyline points="{" ".join(pts)}" fill="none" stroke="{col}" stroke-width="{sw}" opacity="{op}"/>')
    pr0 = trajs["rot_asym"][0]
    for bidx, col in [(1, "#38d4f0"), (2, "#5b8def"), (3, "#ffd166")]:
        svg.append(f'<circle cx="{c2x + pr0[f"x{bidx}"] * c2s:.1f}" cy="{c2y - pr0[f"y{bidx}"] * c2s:.1f}" r="4" fill="{col}" stroke="#0b0e15" stroke-width="1"/>')
    svg.append('<text x="374" y="810" text-anchor="middle" class="lbl">m=(1, 1, 0.75), L=0.15 (5 periods)</text>')
    svg.append('<text x="374" y="824" text-anchor="middle" class="ps">Precesses 142.5 deg/orbit; survives 1000+T</text>')

    # =========================================================================
    # PANEL D: Montgomery's Shape Sphere S^2
    # =========================================================================
    svg.append('<text x="526" y="486" class="pt">D. Montgomery&apos;s Shape Sphere S²</text>')
    svg.append('<text x="526" y="502" class="ps">Figure-eight dodges all 3 equatorial binary collisions; chaos falls into one</text>')

    sx, sy, sR = 745.0, 658.0, 126.0
    az, el = math.radians(18.0), math.radians(22.0)
    caz, saz, cel, sel = math.cos(az), math.sin(az), math.cos(el), math.sin(el)

    def proj_s2(w1: float, w2: float, w3: float) -> tuple[float, float, float]:
        x1 = -saz * w1 + caz * w2
        y1 =  caz * w1 + saz * w2
        z1 = w3
        X = sx + sR * x1
        Y = sy - sR * (z1 * cel - y1 * sel)
        Z = y1 * cel + z1 * sel
        return X, Y, Z

    svg.append(
        '<defs><radialGradient id="sg" cx="38%" cy="32%" r="65%">'
        '<stop offset="0%" stop-color="#1d2b48"/><stop offset="70%" stop-color="#101728"/><stop offset="100%" stop-color="#090d16"/>'
        "</radialGradient></defs>"
    )
    svg.append(f'<circle cx="{sx:.1f}" cy="{sy:.1f}" r="{sR:.1f}" fill="url(#sg)" stroke="#39496b" stroke-width="1.4"/>')

    def draw_s2_curve(coords: list[tuple[float, float, float]], stroke_f: str, stroke_b: str,
                      w_f: float, w_b: float, dash_f: str = "", dash_b: str = "3,3") -> None:
        seg_pts: list[str] = []
        seg_front: bool | None = None
        for w1, w2, w3 in coords:
            X, Y, Z = proj_s2(w1, w2, w3)
            is_f = Z >= 0.0
            if seg_front is not None and is_f != seg_front and len(seg_pts) >= 2:
                st = stroke_f if seg_front else stroke_b
                sw = w_f if seg_front else w_b
                da = f' stroke-dasharray="{dash_f if seg_front else dash_b}"' if (dash_f if seg_front else dash_b) else ""
                svg.append(f'<polyline points="{" ".join(seg_pts)}" fill="none" stroke="{st}" stroke-width="{sw}"{da}/>')
                seg_pts = [seg_pts[-1]]
            seg_pts.append(f"{X:.1f},{Y:.1f}")
            seg_front = is_f
        if len(seg_pts) >= 2 and seg_front is not None:
            st = stroke_f if seg_front else stroke_b
            sw = w_f if seg_front else w_b
            da = f' stroke-dasharray="{dash_f if seg_front else dash_b}"' if (dash_f if seg_front else dash_b) else ""
            svg.append(f'<polyline points="{" ".join(seg_pts)}" fill="none" stroke="{st}" stroke-width="{sw}"{da}/>')

    eq_pts = [(math.cos(2 * math.pi * k / 180), math.sin(2 * math.pi * k / 180), 0.0) for k in range(181)]
    draw_s2_curve(eq_pts, "#4c618a", "#25314a", 1.3, 0.9, "", "3,3")
    for lon_deg in [0, 60, 120]:
        lr = math.radians(lon_deg)
        mer = [(math.cos(lr) * math.cos(t), math.sin(lr) * math.cos(t), math.sin(t))
               for t in [-math.pi + 2 * math.pi * k / 120 for k in range(121)]]
        draw_s2_curve(mer, "#23304a", "#182034", 0.8, 0.6, "", "2,3")

    colls = [
        (-1.0, 0.0, "r1=r2 (back)"),
        (0.5,  0.5 * math.sqrt(3.0), "r2=r3"),
        (0.5, -0.5 * math.sqrt(3.0), "r1=r3"),
    ]
    # Back collision marker behind front trajectories
    for w1c, w2c, txt in colls:
        X, Y, Z = proj_s2(w1c, w2c, 0.0)
        if Z < 0:
            svg.append(f'<circle cx="{X:.1f}" cy="{Y:.1f}" r="4.2" fill="#ff4d6d" stroke="#ffffff" stroke-width="0.9" opacity="0.50"/>')
            svg.append(f'<text x="{X + 9:.1f}" y="{Y - 6:.1f}" text-anchor="start" class="ps" fill="#c97284">{txt}</text>')

    ch_pts = [(p["w1"], p["w2"], p["w3"]) for p in trajs["chaos"][::3]]
    draw_s2_curve(ch_pts, "#c084fc", "#5c397a", 1.15, 0.7, "", "2,3")

    tw_pts = [(p["w1"], p["w2"], p["w3"]) for p in trajs["twin"][::3]]
    draw_s2_curve(tw_pts, "#ff6b6b", "#7a3338", 1.5, 0.9, "4,2", "2,3")

    st_pts = [(p["w1"], p["w2"], p["w3"]) for p in trajs["stable"][::3]]
    draw_s2_curve(st_pts, "#ffd166", "#8c7238", 2.5, 1.3, "", "3,3")

    for w3p, txt in [(1.0, "Lagrange (+1)"), (-1.0, "Lagrange (-1)")]:
        X, Y, _ = proj_s2(0.0, 0.0, w3p)
        svg.append(f'<circle cx="{X:.1f}" cy="{Y:.1f}" r="3.6" fill="#4ade80" stroke="#0b0e15" stroke-width="1"/>')
        svg.append(f'<text x="{X + 10:.1f}" y="{Y + 4:.1f}" class="ps" fill="#7be8a2">{txt}</text>')

    # Front collision markers on top
    for w1c, w2c, txt in colls:
        X, Y, Z = proj_s2(w1c, w2c, 0.0)
        if Z >= 0:
            svg.append(f'<circle cx="{X:.1f}" cy="{Y:.1f}" r="4.8" fill="#ff4d6d" stroke="#ffffff" stroke-width="1.2"/>')
            dx = -10 if X < sx else 10
            anc = "end" if X < sx else "start"
            svg.append(f'<text x="{X + dx:.1f}" y="{Y + 4:.1f}" text-anchor="{anc}" class="lblb" fill="#ff8fa3">{txt}</text>')

    svg.append('<line x1="532" y1="822" x2="554" y2="822" stroke="#ffd166" stroke-width="2.5"/>')
    svg.append('<text x="560" y="826" class="lbl">Figure-8</text>')
    svg.append('<line x1="622" y1="822" x2="644" y2="822" stroke="#ff6b6b" stroke-width="1.6" stroke-dasharray="4,2"/>')
    svg.append('<text x="650" y="826" class="lbl">Twin</text>')
    svg.append('<line x1="692" y1="822" x2="714" y2="822" stroke="#c084fc" stroke-width="1.4"/>')
    svg.append('<text x="720" y="826" class="lbl">Chaotic escape</text>')
    svg.append('<circle cx="820" cy="822" r="4" fill="#ff4d6d" stroke="#fff" stroke-width="1"/>')
    svg.append('<text x="829" y="826" class="lbl">Binary collisions</text>')

    svg.append("</svg>")
    out_svg = HERE / "fig8_geometry_and_bifurcations.svg"
    out_svg.write_text("\n".join(svg), encoding="utf-8")
    print(f"Wrote {out_svg} ({W}x{H})")


if __name__ == "__main__":
    build_kam_atlas_png()
    build_geometry_and_bifurcations_svg()
