use Test;
use lib 'lib';
use Noise::Simplex::Native;

# Regression test: passing huge coordinates (high-octave fBm of
# unbounded base coords; |coord| > 2^31, possibly > 2^63) must not
# trigger UB in the C side. Internally, the perm-table indexing
# does `floor(x + s)` then needs the low 8 bits of the result;
# the naive `(int)((long) i_f & 255)` is UB when i_f exceeds
# LONG_MAX (and obviously for NaN / Inf), so we use a fmod-based
# fallback path via mod256_double().
#
# This test exercises that fallback path and asserts the algorithm
# still produces valid noise output (in [-1, 1] modulo the standard
# scale-factor slop).

plan 5;

my $simplex = Noise::Simplex::Native::Simplex.new(seed => 12345);
my &n2d = $simplex.create-noise2d;
my &n3d = $simplex.create-noise3d;

# 1. Normal-range coord — fast path.
{
    my $v = n2d(123e0, 456e0);
    ok -1.5 < $v < 1.5, "normal coord: 2D in range ($v)";
}

# 2. Coord just over 2^31 — slow path edge.
{
    my $v = n2d(2_147_483_649e0, 2_147_483_649e0);
    ok -1.5 < $v < 1.5, "2^31+1 coord: 2D in range ($v)";
}

# 3. Astronomical coord — well past 2^63, slow path.
{
    my $v = n2d(1e25, 1e25);
    ok $v.defined && -1.5 < $v < 1.5,
       "1e25 coord: 2D in range, no segfault ($v)";
}

# 4. Negative huge coord.
{
    my $v = n3d(-1e20, 1e20, 1e15);
    ok $v.defined && -1.5 < $v < 1.5,
       "mixed huge ±1e20 coord: 3D in range, no segfault ($v)";
}

# 5. Bulk-fill at huge origin shouldn't crash either.
{
    my $bulk = $simplex.fill-noise2d-grid(
        :x0(1e20), :dx(1e0), :w(8),
        :y0(1e20), :dy(1e0), :h(8),
    );
    my $all-finite = True;
    for ^($bulk.elems) -> Int $i {
        $all-finite = False unless $bulk[$i].defined && -1.5 < $bulk[$i] < 1.5;
    }
    ok $all-finite, "bulk-fill at 1e20 origin: all 64 samples in range";
}

done-testing;
