#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Iterator.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/AudioParam.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/WebAudio/AudioParam.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

void AudioParamConstructor::initialize(JS::Realm& realm, JS::NativeFunction& object)
{
    auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;

    
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "AudioParam"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<AudioParamPrototype>(realm, "AudioParam"_fly_string), 0);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> AudioParamConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "AudioParamConstructor::construct");
    return constructor.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "AudioParam");
}

void AudioParamPrototype::initialize(JS::Realm& realm, JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;

    object.set_prototype(realm.intrinsics().object_prototype());

    auto value_id = "value"_utf16_fly_string;
    auto native_value_getter = JS::NativeFunction::create(realm, value_getter, 0, value_id, &realm, "get"sv);
    auto native_value_setter = JS::NativeFunction::create(realm, value_setter, 1, value_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto value_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(value_id, native_value_getter, native_value_setter, value_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto automation_rate_id = "automationRate"_utf16_fly_string;
    auto native_automation_rate_getter = JS::NativeFunction::create(realm, automation_rate_getter, 0, automation_rate_id, &realm, "get"sv);
    auto native_automation_rate_setter = JS::NativeFunction::create(realm, automation_rate_setter, 1, automation_rate_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto automation_rate_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(automation_rate_id, native_automation_rate_getter, native_automation_rate_setter, automation_rate_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto default_value_id = "defaultValue"_utf16_fly_string;
    auto native_default_value_getter = JS::NativeFunction::create(realm, default_value_getter, 0, default_value_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_default_value_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto default_value_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(default_value_id, native_default_value_getter, native_default_value_setter, default_value_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto min_value_id = "minValue"_utf16_fly_string;
    auto native_min_value_getter = JS::NativeFunction::create(realm, min_value_getter, 0, min_value_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_min_value_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto min_value_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(min_value_id, native_min_value_getter, native_min_value_setter, min_value_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto max_value_id = "maxValue"_utf16_fly_string;
    auto native_max_value_getter = JS::NativeFunction::create(realm, max_value_getter, 0, max_value_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_max_value_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto max_value_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(max_value_id, native_max_value_getter, native_max_value_setter, max_value_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    object.define_native_function(realm, "setValueAtTime"_utf16_fly_string, set_value_at_time, 2, default_attributes);

    object.define_native_function(realm, "linearRampToValueAtTime"_utf16_fly_string, linear_ramp_to_value_at_time, 2, default_attributes);

    object.define_native_function(realm, "exponentialRampToValueAtTime"_utf16_fly_string, exponential_ramp_to_value_at_time, 2, default_attributes);

    object.define_native_function(realm, "setTargetAtTime"_utf16_fly_string, set_target_at_time, 3, default_attributes);

    object.define_native_function(realm, "setValueCurveAtTime"_utf16_fly_string, set_value_curve_at_time, 3, default_attributes);

    object.define_native_function(realm, "cancelScheduledValues"_utf16_fly_string, cancel_scheduled_values, 1, default_attributes);

    object.define_native_function(realm, "cancelAndHoldAtTime"_utf16_fly_string, cancel_and_hold_at_time, 1, default_attributes);

    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "AudioParam"_utf16), JS::Attribute::Configurable);
}

void AudioParamPrototype::define_unforgeable_attributes(JS::Realm& realm, [[maybe_unused]] JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
}

[[maybe_unused]] static JS::ThrowCompletionOr<WebAudio::AudioParam*> impl_from(JS::VM& vm, JS::Value js_value)
{

    if (auto impl = js_value.as_if<WebAudio::AudioParam>())
        return impl.ptr();
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "AudioParam");
}

[[maybe_unused]] static JS::ThrowCompletionOr<WebAudio::AudioParam*> impl_from(JS::VM& vm)
{
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &vm.current_realm()->global_object();
    return impl_from(vm, this_value);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::value_getter)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::value_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->value(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::automation_rate_getter)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::automation_rate_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->automation_rate(); }));

    return JS::PrimitiveString::create(vm, idl_enum_to_string(R));
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::default_value_getter)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::default_value_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->default_value(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::min_value_getter)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::min_value_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->min_value(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::max_value_getter)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::max_value_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->max_value(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::value_setter)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::value_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] WebAudio::AudioParam* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(V.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "value");
        return x;
    }(); }));

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_value(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::automation_rate_setter)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::automation_rate_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] WebAudio::AudioParam* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> attribute's type is an enumeration
        // 1. Let S be ? ToString(V).
        auto maybe_idl_value = throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_automation_rate(vm, V); });

        // 2. If S is not one of the enumeration's values, then return undefined.
        if (maybe_idl_value.is_error())
            return JS::js_undefined();

        // 3. Otherwise, idlValue is the enumeration value equal to S.
        auto idl_value = maybe_idl_value.release_value();

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_automation_rate(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::set_value_at_time)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::set_value_at_time");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::AudioParam* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "setValueAtTime", "2");

    auto arg0 = vm.argument(0);
    auto value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(arg0.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "value");
        return x;
    }(); }));

    auto arg1 = vm.argument(1);
    auto start_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg1.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "startTime");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_value_at_time(value, start_time); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::linear_ramp_to_value_at_time)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::linear_ramp_to_value_at_time");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::AudioParam* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "linearRampToValueAtTime", "2");

    auto arg0 = vm.argument(0);
    auto value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(arg0.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "value");
        return x;
    }(); }));

    auto arg1 = vm.argument(1);
    auto end_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg1.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "endTime");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->linear_ramp_to_value_at_time(value, end_time); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::exponential_ramp_to_value_at_time)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::exponential_ramp_to_value_at_time");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::AudioParam* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "exponentialRampToValueAtTime", "2");

    auto arg0 = vm.argument(0);
    auto value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(arg0.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "value");
        return x;
    }(); }));

    auto arg1 = vm.argument(1);
    auto end_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg1.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "endTime");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->exponential_ramp_to_value_at_time(value, end_time); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::set_target_at_time)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::set_target_at_time");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::AudioParam* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 3)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "setTargetAtTime", "3");

    auto arg0 = vm.argument(0);
    auto target = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(arg0.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "target");
        return x;
    }(); }));

    auto arg1 = vm.argument(1);
    auto start_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg1.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "startTime");
        return x;
    }(); }));

    auto arg2 = vm.argument(2);
    auto time_constant = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(arg2.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "timeConstant");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_target_at_time(target, start_time, time_constant); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::set_value_curve_at_time)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::set_value_curve_at_time");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::AudioParam* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 3)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "setValueCurveAtTime", "3");

    auto arg0 = vm.argument(0);
    auto values = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Vector<float>> {
        if (!arg0.is_object())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, arg0);

        auto method = TRY(arg0.get_method(vm, vm.well_known_symbol_iterator()));
        if (!method)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, arg0);

        return TRY([&]() -> JS::ThrowCompletionOr<Vector<float>> {
        // To create an IDL value of type sequence<T> given an iterable iterable and an iterator getter method, perform the following steps:
        // 1. Let iteratorRecord be ? GetIteratorFromMethod(iterable, method).
        auto iterator = TRY(JS::get_iterator_from_method(vm, arg0, *method));

        Vector<float> sequence;

        // 2. Initialize i to be 0.
        // 3. Repeat
        for (;;) {
            // 1. Let next be ? IteratorStepValue(iteratorRecord).
            auto next = TRY(JS::iterator_step_value(vm, iterator));

            // 2. If next is done, then return an IDL sequence value of type sequence<T> of length i, where the value of the element at index j is Sj.
            if (!next.has_value())
                break;

            // 3. Initialize Si to the result of converting next to an IDL value of type T.
            auto next_value = next.release_value();
            auto sequence_item = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(next_value.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "values");
        return x;
    }(); }));

            // 4. Set i to i + 1.
            sequence.append(sequence_item);
        }

        return sequence;
    }());
    }(); }));

    auto arg1 = vm.argument(1);
    auto start_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg1.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "startTime");
        return x;
    }(); }));

    auto arg2 = vm.argument(2);
    auto duration = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg2.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "duration");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_value_curve_at_time(values, start_time, duration); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::cancel_scheduled_values)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::cancel_scheduled_values");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::AudioParam* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelScheduledValues");

    auto arg0 = vm.argument(0);
    auto cancel_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg0.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "cancelTime");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->cancel_scheduled_values(cancel_time); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AudioParamPrototype::cancel_and_hold_at_time)
{
    WebIDL::log_trace(vm, "AudioParamPrototype::cancel_and_hold_at_time");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::AudioParam* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelAndHoldAtTime");

    auto arg0 = vm.argument(0);
    auto cancel_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg0.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "cancelTime");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->cancel_and_hold_at_time(cancel_time); }));
    return JS::Value(R);
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<AutomationRate> convert_to_idl_value_for_automation_rate(JS::VM& vm, JS::Value value)
{
    // 1. Let S be the result of calling ? ToString(V).
    auto value_as_string = TRY(value.to_utf16_string(vm));

    // 2. If S is not one of E’s enumeration values, then throw a TypeError.
    // 3. Return the enumeration value of type E that is equal to S.
    if (value_as_string == "a-rate"sv)
        return AutomationRate::ARate;
    if (value_as_string == "k-rate"sv)
        return AutomationRate::KRate;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "AutomationRate");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(AutomationRate value)
{
    // The result of converting an IDL enumeration type value to a JavaScript value is the String value that represents the same sequence of code units as the enumeration value.
    switch (value) {
    case AutomationRate::ARate:
        return "a-rate"_utf16;
    case AutomationRate::KRate:
        return "k-rate"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
