// Standalone tests for reasampler::instrument::ui::envelope_overlay — no VST3, no REAPER, no
// framework. Same fast assert loop as the sibling pure tests. Assert the staged-envelope ->
// polyline FORWARD map for BOTH layout policies: the AHDSR bounded schematic with its
// RIGHT-ANCHORED release, and the sustain-less AHD laid 1:1 over the waveform's time axis.
//
// Covers: timeToX / levelToY (linear maps, edge clamps, past-end clamped to right-1, no 32-bit
// overflow on huge times, degenerate area/duration); gateStageSlotPx; the AHDSR polyline (node
// order, levels, the TAPERED stage placement and its legibility at both ends of the range,
// release anchored at the right edge, the sustain plateau reaching the edge at zero release,
// per-segment separation at the tier-0 defaults, overrun compression, every vertex in-bounds);
// splitAhdSeconds (A+H+D never exceeds the span, hold at 0% and 100%); the AHD polyline (1:1 with
// the time axis, origin offset); curve knots (present only on sloped non-zero segments, height
// following the exponent, and — swept across ODD and EVEN pixel spans, not one fixture's width —
// sitting on the curve its own vertices imply rather than always the segment's exact midpoint);
// the degenerate flat baseline.

#include "../src/core/instrument/ui/envelope_overlay.h"

#include "../src/core/instrument/ui/sample_bands.h"  // the editor floor the legibility test uses

#include <cmath>
#include <cstdio>
#include <vector>

using namespace reasampler;
using namespace reasampler::instrument::ui;

static int g_fail = 0;
#define CHECK(cond) do { if(!(cond)) { \
    std::printf("FAIL line %d: %s\n", __LINE__, #cond); ++g_fail; } } while(0)

static OverlayArea overlayOf(const Rect& r) { return OverlayArea{r}; }

// A comfortable overlay area: 1000px wide, 100px tall, offset so left/top != 0 (catches origin
// bugs). Under levelToY the level span is height-1 = 99 rows.
static Rect wideArea() { return Rect::ltrb(20, 10, 1020, 110); }  // width 1000, height 100

static bool findNode(const std::vector<EnvVertex>& poly, EnvNode node, EnvVertex& out) {
    for (const EnvVertex& v : poly) {
        if (v.node == node) { out = v; return true; }
    }
    return false;
}
static bool hasNode(const std::vector<EnvVertex>& poly, EnvNode node) {
    EnvVertex v;
    return findNode(poly, node, v);
}

static StageEnvelope ahdsr(double a, double h, double d, double sus, double r) {
    StageEnvelope e;
    e.kind = EnvKind::Ahdsr;
    e.attackSeconds = a;
    e.holdSeconds = h;
    e.decaySeconds = d;
    e.sustainLevel = sus;
    e.releaseSeconds = r;
    return e;
}

static StageEnvelope ahd(double a, double d, double frac, double origin, double span) {
    StageEnvelope e;
    e.kind = EnvKind::Ahd;
    e.attackSeconds = a;
    e.decaySeconds = d;
    e.holdFraction = frac;
    e.originSeconds = origin;
    e.spanSeconds = span;
    return e;
}

// --- timeToX / levelToY -------------------------------------------------------

static void testTimeToXEndpoints() {
    const Rect a = wideArea();
    CHECK(timeToX(a, 2.0, 0.0) == a.x);            // t=0 -> left
    CHECK(timeToX(a, 2.0, 2.0) == a.right() - 1);  // t=total -> last in-bounds column
    CHECK(timeToX(a, 2.0, 1.0) == a.x + 500);      // midpoint
}

static void testTimeToXClampsBothEnds() {
    const Rect a = wideArea();
    CHECK(timeToX(a, 2.0, -0.5) == a.x);
    CHECK(timeToX(a, 2.0, 3.0) == a.right() - 1);
    // A HUGE t must clamp in double space, not overflow the integer cast (32-bit long on
    // Windows would wrap to LONG_MIN and pin to the WRONG edge).
    CHECK(timeToX(a, 2.0, 1e15) == a.right() - 1);
}

static void testLevelToY() {
    const Rect a = wideArea();
    CHECK(levelToY(a, 1.0) == a.y);                 // level 1 -> top row
    CHECK(levelToY(a, 0.0) == a.bottom() - 1);      // level 0 -> bottom row
    CHECK(levelToY(a, 0.5) == a.y + 50);            // 99-row span, rounded
    CHECK(levelToY(a, 5.0) == a.y);                 // clamps
    CHECK(levelToY(a, -5.0) == a.bottom() - 1);
}

static void testDegenerateAreaAndDuration() {
    CHECK(timeToX(Rect{}, 2.0, 1.0) == 0);
    CHECK(timeToX(wideArea(), 0.0, 1.0) == wideArea().x);
    CHECK(levelToY(Rect{}, 0.5) == 0);
    CHECK(gateStageSlotPx(Rect{}) == 0.0);
}

// The literal slot width, independent of any sample duration: usable px = canvas width minus the
// last column minus 4 node-separation bases, split four ways. A stage then occupies its own
// TAPERED fraction of that slot, which is what makes a dragged handle track the cursor at both
// ends of the range — a scale regression here is exactly what a relational-only check misses.
static void testGateStageSlotPx() {
    // 967 / 4 px, pinned as a literal — restating the formula with the same named constants
    // would let a change to kGateNodeSepPx move both sides and pass silently.
    CHECK(gateStageSlotPx(wideArea()) == 241.75);
    CHECK(gateStageSlotPx(Rect::ltrb(5, 5, 5, 45)) == 0.0);   // zero-width area -> 0
    CHECK(gateStageSlotPx(Rect::ltrb(0, 0, 10, 10)) > 0.0);   // tiny area: usable floors at 1px, > 0
}

// --- the AHDSR schematic ------------------------------------------------------

static void testAhdsrNodeOrderAndLevels() {
    const Rect a = wideArea();
    const std::vector<EnvVertex> poly =
        buildEnvelopePolyline(ahdsr(0.2, 0.1, 0.3, 0.5, 0.4), overlayOf(a), 4.0);
    EnvVertex v;
    CHECK(poly.size() >= 6);
    CHECK(poly[0].node == EnvNode::Origin && poly[0].level == 0.0);
    CHECK(poly[1].node == EnvNode::AttackEnd && poly[1].level == 1.0);
    CHECK(poly[2].node == EnvNode::HoldEnd && poly[2].level == 1.0);
    CHECK(poly[3].node == EnvNode::DecayEnd && poly[3].level == 0.5);
    CHECK(poly[4].node == EnvNode::ReleaseStart && poly[4].level == 0.5);
    CHECK(poly[5].node == EnvNode::ReleaseEnd && poly[5].level == 0.0);
    // Monotone in x across the traced line.
    for (std::size_t i = 1; i < 6; ++i) CHECK(poly[i].x >= poly[i - 1].x);
    // Every vertex in-bounds.
    for (const EnvVertex& p : poly) {
        CHECK(p.x >= a.x && p.x <= a.right() - 1);
        CHECK(p.y >= a.y && p.y <= a.bottom() - 1);
    }
    CHECK(findNode(poly, EnvNode::ReleaseEnd, v));
    CHECK(v.x == a.right() - 1);  // ANCHORED, whatever the release is
}

// The literal per-node x placement, hand-derived from the documented formula (slot = 241.75 px
// per testGateStageSlotPx; each timed stage is prefixed by the kGateNodeSepPx=8 base and occupies
// slot x timeNormFromSeconds(t) of its own slot; L = ln(1 + 10/0.003) = 8.112028):
//   attack .25s  -> norm ln(84.3333)/L  = 0.546677 -> 8 + 132.159 = 140.159       -> px 140
//   hold   .05s  -> norm ln(17.6667)/L  = 0.354007 -> 140.159 + 8 + 85.581 = 233.740 -> px 234
//   decay  .5s   -> norm ln(167.667)/L  = 0.631385 -> 233.740 + 8 + 152.637 = 394.377 -> px 394
//   plateau 1s   -> norm ln(334.333)/L  = 0.716493 -> 999 - 8 - 173.211 = 817.789    -> px 818
//   release end pinned at the last column, 999.
// A literal regression pin — no relational or bounds-only check catches a formula-shape change
// the way an exact pixel count does.
static void testAhdsrSchematicPlacement() {
    const Rect a = wideArea();
    const std::vector<EnvVertex> poly =
        buildEnvelopePolyline(ahdsr(0.25, 0.05, 0.5, 0.5, 1.0), overlayOf(a), 4.0);
    EnvVertex v;
    CHECK(findNode(poly, EnvNode::AttackEnd, v)    && v.x == a.x + 140);
    CHECK(findNode(poly, EnvNode::HoldEnd, v)      && v.x == a.x + 234);
    CHECK(findNode(poly, EnvNode::DecayEnd, v)     && v.x == a.x + 394);
    CHECK(findNode(poly, EnvNode::ReleaseStart, v) && v.x == a.x + 818);
    CHECK(findNode(poly, EnvNode::ReleaseEnd, v)   && v.x == a.x + 999);
}

// The legibility the tapered axis exists for, at BOTH ends of the raised range. Linear-in-seconds
// put the 3 ms default attack 0.07 px from the origin at a 10 s ceiling — indistinguishable from
// zero and impossible to grab. Asserted at the editor's own floor width, not a comfortable one.
static void testTaperedAxisKeepsBothEndsOfTheRangeLegible() {
    const Rect floorArea = Rect::ltrb(0, 0, kEditorMinWidth - 2 * kPad, 100);
    const std::vector<EnvVertex> poly =
        buildEnvelopePolyline(ahdsr(0.003, 0.0, 0.0, 1.0, 0.060), overlayOf(floorArea), 4.0);
    EnvVertex origin, attack;
    CHECK(findNode(poly, EnvNode::Origin, origin));
    CHECK(findNode(poly, EnvNode::AttackEnd, attack));
    // Well clear of the grab radius, so the default attack is a real handle rather than a node
    // sitting on the origin.
    CHECK(attack.x - origin.x >= 20);

    // And a maxed stage still lands its end node at its slot's edge: the taper's norm-1 end and
    // the schematic's canvas edge are the same place, which is the anchor the policy rests on.
    const std::vector<EnvVertex> maxed = buildEnvelopePolyline(
        ahdsr(kGateStageMaxSeconds, 0.0, 0.0, 1.0, 0.0), overlayOf(floorArea), 4.0);
    EnvVertex maxAttack;
    CHECK(findNode(maxed, EnvNode::AttackEnd, maxAttack));
    const double slot = gateStageSlotPx(floorArea);
    CHECK(maxAttack.x == floorArea.x + static_cast<int>(kGateNodeSepPx + slot + 0.5));
}

// The AHDSR schematic is scaled by the PARAM domain, NOT the capture length: the same params
// produce the SAME polyline whether totalSeconds is 0.3 or 10 (gatePolyline doesn't even take
// totalSeconds — only the sustain-less AHD's x-axis is wall-clock/PCM-aligned).
static void testGateLayoutIndependentOfSampleDuration() {
    const Rect a = wideArea();
    const StageEnvelope e = ahdsr(0.2, 0.1, 0.3, 0.5, 0.06);
    CHECK(buildEnvelopePolyline(e, overlayOf(a), 0.3) == buildEnvelopePolyline(e, overlayOf(a), 10.0));
}

// The layout failure this policy exists to fix: at zero release the sustain plateau must run to
// (near) the right edge instead of the figure bunching left.
static void testZeroReleasePutsTheSustainPlateauAtTheRightEdge() {
    const Rect a = wideArea();
    const std::vector<EnvVertex> poly =
        buildEnvelopePolyline(ahdsr(0.05, 0.0, 0.05, 0.7, 0.0), overlayOf(a), 4.0);
    EnvVertex plateau, end;
    CHECK(findNode(poly, EnvNode::ReleaseStart, plateau));
    CHECK(findNode(poly, EnvNode::ReleaseEnd, end));
    CHECK(end.x == a.right() - 1);
    // One node separation short of the edge — the plateau spans essentially the whole canvas.
    CHECK(plateau.x == a.right() - 1 - kGateNodeSepPx);
    EnvVertex decay;
    CHECK(findNode(poly, EnvNode::DecayEnd, decay));
    CHECK(plateau.x - decay.x > a.width / 2);
}

// The release END never moves; the release START is what a longer release pushes left.
static void testReleaseGrowsLeftwardFromTheAnchor() {
    const Rect a = wideArea();
    EnvVertex shortStart, longStart, shortEnd, longEnd;
    const std::vector<EnvVertex> shortR =
        buildEnvelopePolyline(ahdsr(0.1, 0.0, 0.1, 0.5, 0.1), overlayOf(a), 4.0);
    const std::vector<EnvVertex> longR =
        buildEnvelopePolyline(ahdsr(0.1, 0.0, 0.1, 0.5, 1.5), overlayOf(a), 4.0);
    CHECK(findNode(shortR, EnvNode::ReleaseStart, shortStart));
    CHECK(findNode(longR, EnvNode::ReleaseStart, longStart));
    CHECK(findNode(shortR, EnvNode::ReleaseEnd, shortEnd));
    CHECK(findNode(longR, EnvNode::ReleaseEnd, longEnd));
    CHECK(longStart.x < shortStart.x);
    CHECK(shortEnd.x == longEnd.x);
}

// Tier-0 defaults are zero hold and zero decay; every node still has to be independently
// grabbable, which is what the per-segment separation base buys.
static void testTierZeroDefaultsKeepEveryNodeDistinct() {
    const Rect a = wideArea();
    const std::vector<EnvVertex> poly =
        buildEnvelopePolyline(ahdsr(0.003, 0.0, 0.0, 1.0, 0.060), overlayOf(a), 4.0);
    for (std::size_t i = 1; i < 6; ++i) {
        CHECK(poly[i].x - poly[i - 1].x >= kGateNodeSepPx - 1);
    }
}

// Every stage maxed: the schematic exactly fills the canvas, the plateau collapses to its
// minimum gap, and nothing escapes the rect.
static void testMaxedStagesCompressWithoutOverrunning() {
    const Rect a = wideArea();
    const double m = kGateStageMaxSeconds;
    const std::vector<EnvVertex> poly =
        buildEnvelopePolyline(ahdsr(m, m, m, 0.5, m), overlayOf(a), 4.0);
    for (std::size_t i = 1; i < 6; ++i) {
        CHECK(poly[i].x >= poly[i - 1].x);
        CHECK(poly[i].x <= a.right() - 1);
        // The compression exists to preserve MINIMUM gaps under overrun, not merely
        // non-strict monotonicity — a compression that let two nodes collapse onto one
        // pixel would still pass a `>=` check but defeat the whole point of kGateNodeSepPx.
        CHECK(poly[i].x - poly[i - 1].x >= kGateNodeSepPx - 1);
    }
    EnvVertex end;
    CHECK(findNode(poly, EnvNode::ReleaseEnd, end));
    CHECK(end.x == a.right() - 1);
}

// Absurd stage values must clamp in double space, not overflow the integer cast (32-bit long
// on Windows would wrap negative and land on the WRONG edge) — a regression named for the bug
// it once was. gateVtx's own double-space clamp is what this exercises.
static void testAbsurdReleaseValueStaysInBounds() {
    const Rect a = wideArea();
    StageEnvelope huge = ahdsr(0.1, 0.1, 0.1, 0.5, 0.1);
    huge.releaseSeconds = 1e12;
    for (const EnvVertex& v : buildEnvelopePolyline(huge, overlayOf(a), 4.0)) {
        CHECK(v.x >= a.x && v.x < a.right());
        CHECK(v.y >= a.y && v.y < a.bottom());
    }
}

// --- the AHD split ------------------------------------------------------------

// The combined-time bound, asserted structurally across the full domains: no (attack, decay,
// fraction) triple can exceed the span, and no clamp on the SUM exists to be exercised.
static void testAhdSplitNeverExceedsTheSpan() {
    const double span = 3.0;
    for (int ai = 0; ai <= 20; ++ai) {
        for (int di = 0; di <= 20; ++di) {
            for (int fi = 0; fi <= 10; ++fi) {
                const StageEnvelope e =
                    ahd(ai * 0.25, di * 0.25, fi * 0.1, 0.0, span);
                const AhdSplit s = splitAhdSeconds(e);
                CHECK(s.attack >= 0.0 && s.hold >= 0.0 && s.decay >= 0.0);
                CHECK(s.total <= span + 1e-9);
                CHECK(std::fabs(s.total - (s.attack + s.hold + s.decay)) < 1e-12);
            }
        }
    }
}

static void testHoldFractionEndpoints() {
    const StageEnvelope none = ahd(0.5, 0.5, 0.0, 0.0, 4.0);
    const AhdSplit s0 = splitAhdSeconds(none);
    CHECK(s0.hold == 0.0);
    CHECK(std::fabs(s0.total - 1.0) < 1e-12);

    const StageEnvelope full = ahd(0.5, 0.5, 1.0, 0.0, 4.0);
    const AhdSplit s1 = splitAhdSeconds(full);
    // 100% of what attack and decay left: 4 - 0.5 - 0.5 = 3.
    CHECK(std::fabs(s1.hold - 3.0) < 1e-12);
    CHECK(std::fabs(s1.total - 4.0) < 1e-12);

    // Attack + decay alone longer than the span: they fit by their own per-stage bounds and the
    // remainder — and therefore hold — is zero. Still no clamp on the sum.
    const AhdSplit s2 = splitAhdSeconds(ahd(3.0, 3.0, 1.0, 0.0, 4.0));
    CHECK(std::fabs(s2.attack - 3.0) < 1e-12);
    CHECK(std::fabs(s2.decay - 1.0) < 1e-12);
    CHECK(s2.hold == 0.0);
    CHECK(std::fabs(s2.total - 4.0) < 1e-12);
}

// --- the AHD polyline ---------------------------------------------------------

// The 1:1 property: a stage boundary at N seconds sits over the waveform at N seconds.
static void testAhdIsOneToOneWithTheTimeAxis() {
    const Rect a = wideArea();
    const double total = 8.0;
    const StageEnvelope e = ahd(1.0, 2.0, 0.5, 1.0, 6.0);
    const std::vector<EnvVertex> poly = buildEnvelopePolyline(e, overlayOf(a), total);
    const AhdSplit s = splitAhdSeconds(e);
    EnvVertex origin, attack, hold, decay;
    CHECK(findNode(poly, EnvNode::Origin, origin));
    CHECK(findNode(poly, EnvNode::AttackEnd, attack));
    CHECK(findNode(poly, EnvNode::HoldEnd, hold));
    CHECK(findNode(poly, EnvNode::DecayEnd, decay));
    CHECK(origin.x == timeToX(a, total, 1.0));
    CHECK(attack.x == timeToX(a, total, 1.0 + s.attack));
    CHECK(hold.x == timeToX(a, total, 1.0 + s.attack + s.hold));
    CHECK(decay.x == timeToX(a, total, 1.0 + s.total));
    // Levels: rises to unity, holds, falls to zero. No sustain-only nodes exist.
    CHECK(origin.level == 0.0 && attack.level == 1.0 && hold.level == 1.0 && decay.level == 0.0);
    CHECK(!hasNode(poly, EnvNode::ReleaseStart));
    CHECK(!hasNode(poly, EnvNode::ReleaseEnd));
    CHECK(!hasNode(poly, EnvNode::ReleaseCurve));
}

// F1 regression: DecayEnd stays at its true wall-clock instant even when that instant coincides
// with HoldEnd's (decay ~ 0) — the 1:1 AHD axis promises N seconds -> N seconds, and a nudge
// away from that instant lies about the shape, including the Trigger default's abrupt cutoff.
// Fails against the prior nudge, which moved DecayEnd right whenever the gap was under
// kGateNodeSepPx.
static void testDecayEndStaysAtItsTrueInstantEvenWhenCoincidentWithHoldEnd() {
    const Rect a = wideArea();
    const double total = 4.0;

    // Short but nonzero decay: the true gap to HoldEnd is a few px, under kGateNodeSepPx, so
    // the retired nudge would have fired here too.
    const StageEnvelope shortDecay = ahd(0.5, 0.02, 1.0, 0.0, 3.0);
    const AhdSplit sShort = splitAhdSeconds(shortDecay);
    EnvVertex decayShort;
    CHECK(findNode(buildEnvelopePolyline(shortDecay, overlayOf(a), total), EnvNode::DecayEnd,
                   decayShort));
    CHECK(decayShort.x == timeToX(a, total, sShort.total));

    // Zero decay (the Trigger AHD default's shape): DecayEnd and HoldEnd share the exact same
    // instant — the abrupt cutoff — and DecayEnd must not be nudged off it.
    const StageEnvelope zeroDecay = ahd(0.5, 0.0, 1.0, 0.0, 3.0);
    const AhdSplit sZero = splitAhdSeconds(zeroDecay);
    const std::vector<EnvVertex> polyZero = buildEnvelopePolyline(zeroDecay, overlayOf(a), total);
    EnvVertex decayZero, holdZero;
    CHECK(findNode(polyZero, EnvNode::DecayEnd, decayZero));
    CHECK(findNode(polyZero, EnvNode::HoldEnd, holdZero));
    CHECK(decayZero.x == timeToX(a, total, sZero.total));
    CHECK(decayZero.x == holdZero.x);  // truly coincident, not nudged apart
}

// --- curve knots --------------------------------------------------------------

// A knot rides every sloped stage that has a duration, and none that does not — a zero-length
// stage has no interior to put a handle in.
static void testKnotsRideOnlySlopedNonZeroSegments() {
    const Rect a = wideArea();
    const std::vector<EnvVertex> full =
        buildEnvelopePolyline(ahdsr(0.2, 0.2, 0.2, 0.5, 0.2), overlayOf(a), 4.0);
    CHECK(hasNode(full, EnvNode::AttackCurve));
    CHECK(hasNode(full, EnvNode::DecayCurve));
    CHECK(hasNode(full, EnvNode::ReleaseCurve));

    const std::vector<EnvVertex> flat =
        buildEnvelopePolyline(ahdsr(0.0, 0.2, 0.0, 0.5, 0.0), overlayOf(a), 4.0);
    CHECK(!hasNode(flat, EnvNode::AttackCurve));
    CHECK(!hasNode(flat, EnvNode::DecayCurve));
    CHECK(!hasNode(flat, EnvNode::ReleaseCurve));

    const std::vector<EnvVertex> ahdPoly =
        buildEnvelopePolyline(ahd(0.5, 0.5, 0.5, 0.0, 4.0), overlayOf(a), 4.0);
    CHECK(hasNode(ahdPoly, EnvNode::AttackCurve));
    CHECK(hasNode(ahdPoly, EnvNode::DecayCurve));
    // Every knot is flagged as one and every stage node is not.
    for (const EnvVertex& v : ahdPoly) {
        const bool isKnot = v.node == EnvNode::AttackCurve || v.node == EnvNode::DecayCurve;
        CHECK(v.knot == isKnot);
    }
}

// The knot's HEIGHT is the exponent, read through the shared law: neutral sits at the segment
// midpoint level, a larger exponent pulls the attack knot toward the floor, a smaller one
// toward the ceiling. This is the visible half of the one-model rule.
static void testKnotHeightTracksTheExponent() {
    const Rect a = wideArea();
    StageEnvelope e = ahdsr(0.4, 0.0, 0.0, 1.0, 0.0);
    EnvVertex neutral, steep, shallow;

    e.attackCurve = 1.0;
    CHECK(findNode(buildEnvelopePolyline(e, overlayOf(a), 4.0), EnvNode::AttackCurve, neutral));
    CHECK(std::fabs(neutral.level - 0.5) < 1e-12);   // linear: half way up at half way across
    CHECK(neutral.y == levelToY(a, 0.5));

    e.attackCurve = 4.0;
    CHECK(findNode(buildEnvelopePolyline(e, overlayOf(a), 4.0), EnvNode::AttackCurve, steep));
    CHECK(steep.level < neutral.level);
    CHECK(steep.y > neutral.y);                      // lower on screen

    e.attackCurve = 0.25;
    CHECK(findNode(buildEnvelopePolyline(e, overlayOf(a), 4.0), EnvNode::AttackCurve, shallow));
    CHECK(shallow.level > neutral.level);
    CHECK(shallow.y < neutral.y);

    // The knot sits between its segment's endpoints in x, and inside the canvas in y.
    CHECK(steep.x > a.x && steep.x < a.right() - 1);
    CHECK(steep.y >= a.y && steep.y <= a.bottom() - 1);
}

// --- the knot sits ON its own curve (the reported defect, stated as the gate) -------------

// The general (non-truncated-phi) reading of a knot's level, computed from the vertices
// `buildEnvelopePolyline` actually returned — x0/x1/knotX are all int pixels a caller can read
// off the polyline, so this is a check ON the output, not a restatement of knotVtx's own
// formula. x0 == x1 has no interior (no knot is ever built there).
static double expectedKnotLevel(int x0, int x1, int knotX, double startLevel, double endLevel,
                                double exponent) {
    const double phi = (x1 != x0)
                            ? static_cast<double>(knotX - x0) / static_cast<double>(x1 - x0)
                            : 0.5;
    return startLevel + (endLevel - startLevel) * reasampler::util::curveMap(phi, exponent);
}

// The reported defect, stated as the gate: at every exponent the knot's centre lies on the
// trace, within 1 px. Swept over a range of canvas widths (down to a few pixels of stage span)
// so the check actually exercises ODD pixel spans, where the segment's true midpoint falls
// between two pixels — testKnotHeightTracksTheExponent above sits at a width whose span happens
// to be even, which is exactly the kind of fixture that missed this defect.
static void testKnotSitsOnItsOwnCurveAcrossOddAndEvenSpans() {
    bool sawOdd = false, sawEven = false;
    int worstAhdsr = 0, worstAhd = 0;
    for (int width = 24; width <= 260; width += 3) {
        const Rect a = Rect::ltrb(0, 0, width, 100);
        for (double exp : {util::kCurveMin, 0.3, 1.0, 3.0, util::kCurveMax}) {
            StageEnvelope e = ahdsr(0.4, 0.0, 0.0, 1.0, 0.0);
            e.attackCurve = exp;
            EnvVertex origin, attackEnd, knot;
            const std::vector<EnvVertex> poly = buildEnvelopePolyline(e, overlayOf(a), 4.0);
            if (findNode(poly, EnvNode::Origin, origin) &&
                findNode(poly, EnvNode::AttackEnd, attackEnd) &&
                findNode(poly, EnvNode::AttackCurve, knot)) {
                const int span = attackEnd.x - origin.x;
                if (span > 0) {
                    if (span % 2 == 0) sawEven = true; else sawOdd = true;
                    const double expected =
                        expectedKnotLevel(origin.x, attackEnd.x, knot.x, 0.0, 1.0, exp);
                    const int expectedY = levelToY(a, expected);
                    worstAhdsr = (std::max)(worstAhdsr, std::abs(knot.y - expectedY));
                    CHECK(std::abs(knot.y - expectedY) <= 1);
                }
            }

            StageEnvelope f = ahd(0.4, 0.6, 0.5, 0.0, 3.0);
            f.attackCurve = exp;
            EnvVertex originAhd, attackEndAhd, knotAhd;
            const std::vector<EnvVertex> polyAhd = buildEnvelopePolyline(f, overlayOf(a), 4.0);
            if (findNode(polyAhd, EnvNode::Origin, originAhd) &&
                findNode(polyAhd, EnvNode::AttackEnd, attackEndAhd) &&
                findNode(polyAhd, EnvNode::AttackCurve, knotAhd)) {
                const int span = attackEndAhd.x - originAhd.x;
                if (span > 0) {
                    if (span % 2 == 0) sawEven = true; else sawOdd = true;
                    const double expected = expectedKnotLevel(originAhd.x, attackEndAhd.x,
                                                              knotAhd.x, 0.0, 1.0, exp);
                    const int expectedY = levelToY(a, expected);
                    worstAhd = (std::max)(worstAhd, std::abs(knotAhd.y - expectedY));
                    CHECK(std::abs(knotAhd.y - expectedY) <= 1);
                }
            }
        }
    }
    CHECK(sawOdd);   // the sweep actually exercised an odd-pixel span...
    CHECK(sawEven);  // ...and an even one, so this isn't resting on one fixture's luck.
    std::printf("  worst knot/curve separation: AHDSR %d px, AHD %d px\n", worstAhdsr, worstAhd);
}

// Exponent 1.0 is still a plain straight line even off the segment's exact midpoint — checked
// at a deliberately ODD span so the linear case isn't only proven at the symmetric one.
static void testNeutralExponentIsAStraightLineOffCentre() {
    bool found = false;
    for (int width = 24; width <= 200 && !found; ++width) {
        const Rect a = Rect::ltrb(0, 0, width, 100);
        StageEnvelope e = ahdsr(0.4, 0.0, 0.0, 1.0, 0.0);
        e.attackCurve = util::kCurveNeutral;
        EnvVertex origin, attackEnd, knot;
        const std::vector<EnvVertex> poly = buildEnvelopePolyline(e, overlayOf(a), 4.0);
        if (!findNode(poly, EnvNode::Origin, origin)) continue;
        if (!findNode(poly, EnvNode::AttackEnd, attackEnd)) continue;
        if (!findNode(poly, EnvNode::AttackCurve, knot)) continue;
        const int span = attackEnd.x - origin.x;
        if (span <= 0 || span % 2 == 0) continue;
        found = true;
        const double phi = static_cast<double>(knot.x - origin.x) / static_cast<double>(span);
        CHECK(std::fabs(knot.level - phi) < 1e-12);  // linear: level == phi, exactly
    }
    CHECK(found);  // the sweep must actually land on an odd span
}

// --- degenerate ---------------------------------------------------------------

static void testDegenerateSurfaceYieldsFlatBaseline() {
    const std::vector<EnvVertex> zeroArea =
        buildEnvelopePolyline(ahdsr(0.1, 0.1, 0.1, 0.5, 0.1), overlayOf(Rect{}), 4.0);
    CHECK(zeroArea.size() == 2);
    CHECK(zeroArea[0].level == 0.0 && zeroArea[1].level == 0.0);
    const std::vector<EnvVertex> zeroDur =
        buildEnvelopePolyline(ahd(0.1, 0.1, 0.5, 0.0, 1.0), overlayOf(wideArea()), 0.0);
    CHECK(zeroDur.size() == 2);
}

int main() {
    testTimeToXEndpoints();
    testTimeToXClampsBothEnds();
    testLevelToY();
    testDegenerateAreaAndDuration();
    testGateStageSlotPx();

    testAhdsrNodeOrderAndLevels();
    testAhdsrSchematicPlacement();
    testTaperedAxisKeepsBothEndsOfTheRangeLegible();
    testGateLayoutIndependentOfSampleDuration();
    testZeroReleasePutsTheSustainPlateauAtTheRightEdge();
    testReleaseGrowsLeftwardFromTheAnchor();
    testTierZeroDefaultsKeepEveryNodeDistinct();
    testMaxedStagesCompressWithoutOverrunning();
    testAbsurdReleaseValueStaysInBounds();

    testAhdSplitNeverExceedsTheSpan();
    testHoldFractionEndpoints();
    testAhdIsOneToOneWithTheTimeAxis();
    testDecayEndStaysAtItsTrueInstantEvenWhenCoincidentWithHoldEnd();

    testKnotsRideOnlySlopedNonZeroSegments();
    testKnotHeightTracksTheExponent();
    testKnotSitsOnItsOwnCurveAcrossOddAndEvenSpans();
    testNeutralExponentIsAStraightLineOffCentre();

    testDegenerateSurfaceYieldsFlatBaseline();

    if (g_fail == 0) std::printf("envelope_overlay: all tests passed\n");
    else std::printf("envelope_overlay: %d FAILED\n", g_fail);
    return g_fail == 0 ? 0 : 1;
}
