// envelope_edit.cpp — see envelope_edit.h. Pure inverse map + hit-test; no host types.

#include "envelope_edit.h"

#include <algorithm>
#include <cstdlib>  // std::abs

namespace reasampler::vst {

namespace {

double clamp(double v, double lo, double hi) {
    if (v < lo) return lo;
    if (v > hi) return hi;
    return v;
}

// Seconds represented by one horizontal pixel under the overlay's linear time base. Zero when the
// area is degenerate (the caller then produces no motion). Matches envelope_overlay::timeToX.
double secondsPerPixel(const Rect& area, double totalSeconds) {
    const int w = std::max(0, area.width());
    if (w <= 0 || totalSeconds <= 0.0) return 0.0;
    return totalSeconds / static_cast<double>(w);
}

// Level (0..1) represented by one vertical pixel. levelToY spans (height-1) rows for [0,1], so one
// pixel is 1/(height-1). Zero when degenerate. Matches envelope_overlay::levelToY.
double levelPerPixel(const Rect& area) {
    const int h = std::max(0, area.height());
    if (h <= 1) return 0.0;
    return 1.0 / static_cast<double>(h - 1);
}

// True for the nodes the user can grab-and-drag (Origin + ReleaseStart are draw-only anchors).
bool isDraggable(EnvNode n) {
    switch (n) {
        case EnvNode::Origin:
        case EnvNode::ReleaseStart:
            return false;
        default:
            return true;
    }
}

}  // namespace

NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSeconds, int x, int y) {
    const std::vector<EnvVertex> poly = buildEnvelopePolyline(env, area, totalSeconds);
    // First-match in draw order (deterministic tie-break), skipping non-draggable anchors.
    for (const EnvVertex& v : poly) {
        if (!isDraggable(v.node)) continue;
        if (std::abs(x - v.x) <= kNodeGrabRadius && std::abs(y - v.y) <= kNodeGrabRadius) {
            return NodeHit{true, v.node};
        }
    }
    return NodeHit{false, EnvNode::Origin};
}

AmpEnvelope resolveNodeDrag(const AmpEnvelope& grabEnv, EnvNode node, const Rect& area,
                            double totalSeconds, const EnvClampBounds& bounds,
                            int dxPixels, int dyPixels) {
    AmpEnvelope out = grabEnv;
    if (!isDraggable(node)) return out;

    const double secPerPx = secondsPerPixel(area, totalSeconds);
    if (secPerPx <= 0.0) return out;  // degenerate area / duration — no motion
    const double dSec = static_cast<double>(dxPixels) * secPerPx;

    switch (node) {
        // --- Gate: each cumulative-time node edits its OWN segment duration. Non-negative
        //     durations ARE the monotonic-in-time guarantee (a node can never cross a neighbour
        //     because every segment stays >= 0), so the [0, max] clamp is the whole constraint.
        case EnvNode::AttackEnd:
            out.attackSeconds = clamp(grabEnv.attackSeconds + dSec, 0.0, bounds.maxAttackSeconds);
            break;
        case EnvNode::HoldEnd:
            out.holdSeconds = clamp(grabEnv.holdSeconds + dSec, 0.0, bounds.maxHoldSeconds);
            break;
        case EnvNode::DecayEnd: {
            // Sustain node: X sets decay time, Y sets sustain level (drag DOWN = higher y = lower
            // level, so subtract the level delta).
            out.decaySeconds = clamp(grabEnv.decaySeconds + dSec, 0.0, bounds.maxDecaySeconds);
            const double lvlPerPx = levelPerPixel(area);
            const double dLevel = -static_cast<double>(dyPixels) * lvlPerPx;
            out.sustainLevel = clamp(grabEnv.sustainLevel + dLevel, 0.0, 1.0);
            break;
        }
        case EnvNode::ReleaseEnd:
            out.releaseSeconds =
                clamp(grabEnv.releaseSeconds + dSec, 0.0, bounds.maxReleaseSeconds);
            break;

        // --- Trigger: fades + length are FRACTIONS. X pixels convert to a fraction of the PLAYED
        //     span (fades) or the whole sample (length). Monotonic: fadeIn + fadeOut <= 1 so the
        //     two fade nodes never cross (each clamps against the other), and length in [0, max].
        //
        //     TRIGGER SEAM — CONVERSION REQUIRED ON BOTH PATHS (Wave 2 shell author, read this):
        //     fadeInFraction/fadeOutFraction in AmpEnvelope are fractions of the played span.
        //     TriggerParams (sampler_core.h) stores the corresponding values as SOURCE FRAMES
        //     (fadeInFrames/fadeOutFrames, int64_t). The shell owes a converter on BOTH directions:
        //       pack   (draw):   fadeInFrames/fadeOutFrames -> fraction (needs frameCount + rate)
        //       unpack (commit): fraction -> fadeInFrames/fadeOutFrames (same inputs)
        //     See the TRIGGER SEAM note on AmpEnvelope in envelope_overlay.h for the formula.
        case EnvNode::FadeInEnd: {
            if (dxPixels == 0) break;  // zero-motion grab: no param change, no division
            const double playSeconds = std::max(0.0, grabEnv.lengthFraction) * totalSeconds;
            const double dFrac = playSeconds > 0.0 ? dSec / playSeconds : 0.0;
            const double hi = std::min(bounds.maxFadeInFraction,
                                       1.0 - std::max(0.0, grabEnv.fadeOutFraction));
            out.fadeInFraction = clamp(grabEnv.fadeInFraction + dFrac, 0.0, std::max(0.0, hi));
            break;
        }
        case EnvNode::FadeOutStart: {
            if (dxPixels == 0) break;  // zero-motion grab: no param change, no division
            // FadeOutStart sits at (1 - fadeOut) of the played span; dragging it LEFT (negative dx)
            // lengthens the fade-out. So the fade-out fraction moves OPPOSITE the pixel delta.
            const double playSeconds = std::max(0.0, grabEnv.lengthFraction) * totalSeconds;
            const double dFrac = playSeconds > 0.0 ? -dSec / playSeconds : 0.0;
            const double hi = std::min(bounds.maxFadeOutFraction,
                                       1.0 - std::max(0.0, grabEnv.fadeInFraction));
            out.fadeOutFraction = clamp(grabEnv.fadeOutFraction + dFrac, 0.0, std::max(0.0, hi));
            break;
        }
        case EnvNode::LengthEnd: {
            // LengthEnd sits at lengthFraction of the WHOLE sample; X maps to a fraction of it.
            const double dFrac = totalSeconds > 0.0 ? dSec / totalSeconds : 0.0;
            out.lengthFraction = clamp(grabEnv.lengthFraction + dFrac, 0.0, bounds.maxLengthFraction);
            break;
        }

        case EnvNode::Origin:
        case EnvNode::ReleaseStart:
            break;  // unreachable (isDraggable filtered above), kept for switch exhaustiveness
    }
    return out;
}

}  // namespace reasampler::vst
