#include <AK/String.h>
#include <AK/TypeCasts.h>
#include <AK/Variant.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/Promise.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Animations/Animation.h>
#include <LibWeb/Animations/AnimationEffect.h>
#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Bindings/Animation.h>
#include <LibWeb/Bindings/EventTarget.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/CSS/CSSNumericValue.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

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

    object.set_prototype(&ensure_web_constructor<EventTargetPrototype>(realm, "EventTarget"_fly_string));
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "Animation"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<AnimationPrototype>(realm, "Animation"_fly_string), 0);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> AnimationConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "AnimationConstructor::construct");
    auto& vm = constructor.vm();
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // To internally create a new object implementing the interface Animation:

    // 3.2. Let prototype be ? Get(newTarget, "prototype").
    auto prototype = TRY(new_target.get(vm.names.prototype));

    // 3.3. If Type(prototype) is not Object, then:
    if (!prototype.is_object()) {
        // 1. Let targetRealm be ? GetFunctionRealm(newTarget).
        auto* target_realm = TRY(JS::get_function_realm(vm, new_target));

        // 2. Set prototype to the interface prototype object for interface in targetRealm.
        VERIFY(target_realm);
        prototype = &Bindings::ensure_web_prototype<AnimationPrototype>(*target_realm, "Animation"_fly_string);
    }

    auto arg0 = vm.argument(0);
    GC::Ptr<Animations::AnimationEffect> effect = nullptr;
    if (!arg0.is_undefined())
        effect = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<Animations::AnimationEffect>> {
        GC::Ptr<Animations::AnimationEffect> value;

        if (!arg0.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<Animations::AnimationEffect>> {
        if (auto impl = arg0.as_if<Animations::AnimationEffect>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "AnimationEffect");
    }());
        }
        return value;
    }(); }));

    auto arg1 = vm.argument(1);
    GC::Ptr<Animations::AnimationTimeline> timeline {};
    if (!arg1.is_undefined())
        timeline = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<Animations::AnimationTimeline>> {
        GC::Ptr<Animations::AnimationTimeline> value;

        if (!arg1.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<Animations::AnimationTimeline>> {
        if (auto impl = arg1.as_if<Animations::AnimationTimeline>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "AnimationTimeline");
    }());
        }
        return value;
    }(); }));

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return Animations::Animation::construct_impl(realm, effect, timeline); }));

    // 7. Set instance.[[Prototype]] to prototype.
    VERIFY(prototype.is_object());
    impl->set_prototype(&prototype.as_object());

    // FIXME: Steps 8...11. of the "internally create a new object implementing the interface Animation" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within Animations::Animation::construct_impl().

    return *impl;
}

void AnimationPrototype::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(GC::Ref { ensure_web_prototype<EventTargetPrototype>(realm, "EventTarget"_fly_string) });

    auto id_id = "id"_utf16_fly_string;
    auto native_id_getter = JS::NativeFunction::create(realm, id_getter, 0, id_id, &realm, "get"sv);
    auto native_id_setter = JS::NativeFunction::create(realm, id_setter, 1, id_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto id_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(id_id, native_id_getter, native_id_setter, id_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 effect_id = "effect"_utf16_fly_string;
    auto native_effect_getter = JS::NativeFunction::create(realm, effect_getter, 0, effect_id, &realm, "get"sv);
    auto native_effect_setter = JS::NativeFunction::create(realm, effect_setter, 1, effect_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto effect_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(effect_id, native_effect_getter, native_effect_setter, effect_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 timeline_id = "timeline"_utf16_fly_string;
    auto native_timeline_getter = JS::NativeFunction::create(realm, timeline_getter, 0, timeline_id, &realm, "get"sv);
    auto native_timeline_setter = JS::NativeFunction::create(realm, timeline_setter, 1, timeline_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto timeline_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(timeline_id, native_timeline_getter, native_timeline_setter, timeline_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 start_time_id = "startTime"_utf16_fly_string;
    auto native_start_time_getter = JS::NativeFunction::create(realm, start_time_getter, 0, start_time_id, &realm, "get"sv);
    auto native_start_time_setter = JS::NativeFunction::create(realm, start_time_setter, 1, start_time_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto start_time_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(start_time_id, native_start_time_getter, native_start_time_setter, start_time_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 current_time_id = "currentTime"_utf16_fly_string;
    auto native_current_time_getter = JS::NativeFunction::create(realm, current_time_getter, 0, current_time_id, &realm, "get"sv);
    auto native_current_time_setter = JS::NativeFunction::create(realm, current_time_setter, 1, current_time_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto current_time_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(current_time_id, native_current_time_getter, native_current_time_setter, current_time_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 playback_rate_id = "playbackRate"_utf16_fly_string;
    auto native_playback_rate_getter = JS::NativeFunction::create(realm, playback_rate_getter, 0, playback_rate_id, &realm, "get"sv);
    auto native_playback_rate_setter = JS::NativeFunction::create(realm, playback_rate_setter, 1, playback_rate_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto playback_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(playback_rate_id, native_playback_rate_getter, native_playback_rate_setter, playback_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 play_state_id = "playState"_utf16_fly_string;
    auto native_play_state_getter = JS::NativeFunction::create(realm, play_state_getter, 0, play_state_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_play_state_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto play_state_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(play_state_id, native_play_state_getter, native_play_state_setter, play_state_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 replace_state_id = "replaceState"_utf16_fly_string;
    auto native_replace_state_getter = JS::NativeFunction::create(realm, replace_state_getter, 0, replace_state_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_replace_state_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto replace_state_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(replace_state_id, native_replace_state_getter, native_replace_state_setter, replace_state_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 pending_id = "pending"_utf16_fly_string;
    auto native_pending_getter = JS::NativeFunction::create(realm, pending_getter, 0, pending_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_pending_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto pending_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(pending_id, native_pending_getter, native_pending_setter, pending_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 ready_id = "ready"_utf16_fly_string;
    auto native_ready_getter = JS::NativeFunction::create(realm, ready_getter, 0, ready_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_ready_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto ready_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(ready_id, native_ready_getter, native_ready_setter, ready_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 finished_id = "finished"_utf16_fly_string;
    auto native_finished_getter = JS::NativeFunction::create(realm, finished_getter, 0, finished_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_finished_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto finished_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(finished_id, native_finished_getter, native_finished_setter, finished_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 onfinish_id = "onfinish"_utf16_fly_string;
    auto native_onfinish_getter = JS::NativeFunction::create(realm, onfinish_getter, 0, onfinish_id, &realm, "get"sv);
    auto native_onfinish_setter = JS::NativeFunction::create(realm, onfinish_setter, 1, onfinish_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto onfinish_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(onfinish_id, native_onfinish_getter, native_onfinish_setter, onfinish_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 oncancel_id = "oncancel"_utf16_fly_string;
    auto native_oncancel_getter = JS::NativeFunction::create(realm, oncancel_getter, 0, oncancel_id, &realm, "get"sv);
    auto native_oncancel_setter = JS::NativeFunction::create(realm, oncancel_setter, 1, oncancel_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto oncancel_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(oncancel_id, native_oncancel_getter, native_oncancel_setter, oncancel_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 onremove_id = "onremove"_utf16_fly_string;
    auto native_onremove_getter = JS::NativeFunction::create(realm, onremove_getter, 0, onremove_id, &realm, "get"sv);
    auto native_onremove_setter = JS::NativeFunction::create(realm, onremove_setter, 1, onremove_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto onremove_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(onremove_id, native_onremove_getter, native_onremove_setter, onremove_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, "cancel"_utf16_fly_string, cancel, 0, default_attributes);

    object.define_native_function(realm, "finish"_utf16_fly_string, finish, 0, default_attributes);

    object.define_native_function(realm, "play"_utf16_fly_string, play, 0, default_attributes);

    object.define_native_function(realm, "pause"_utf16_fly_string, pause, 0, default_attributes);

    object.define_native_function(realm, "updatePlaybackRate"_utf16_fly_string, update_playback_rate, 1, default_attributes);

    object.define_native_function(realm, "reverse"_utf16_fly_string, reverse, 0, default_attributes);

    object.define_native_function(realm, "persist"_utf16_fly_string, persist, 0, default_attributes);

    object.define_direct_property("commitStyles"_utf16_fly_string, JS::js_undefined(), default_attributes | JS::Attribute::Unimplemented);

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

void AnimationPrototype::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<Animations::Animation*> impl_from(JS::VM& vm, JS::Value js_value)
{

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

[[maybe_unused]] static JS::ThrowCompletionOr<Animations::Animation*> 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(AnimationPrototype::id_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::id_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->id(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::effect_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::effect_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->effect(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::timeline_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::timeline_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->timeline_for_bindings(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::start_time_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::start_time_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->start_time_for_bindings(); }));

    return R.visit(
        [&](double const& visited_union_value0) -> JS::Value
        {
            return JS::Value(visited_union_value0);
        },
        [&](GC::Ref<CSS::CSSNumericValue> const& visited_union_value1) -> JS::Value
        {
            return JS::Value(visited_union_value1);
        },
        [](Empty) -> JS::Value
        {
            return JS::js_null();
        }
    );
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::current_time_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::current_time_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->current_time_for_bindings(); }));

    return R.visit(
        [&](double const& visited_union_value0) -> JS::Value
        {
            return JS::Value(visited_union_value0);
        },
        [&](GC::Ref<CSS::CSSNumericValue> const& visited_union_value1) -> JS::Value
        {
            return JS::Value(visited_union_value1);
        },
        [](Empty) -> JS::Value
        {
            return JS::js_null();
        }
    );
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::playback_rate_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::playback_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->playback_rate(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::play_state_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::play_state_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->play_state_for_bindings(); }));

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

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::replace_state_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::replace_state_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->replace_state(); }));

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

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::pending_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::pending_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->pending(); }));

    return JS::Value(R);
}

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

    auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {
        // 1. Let idlObject be null.
        [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));
        auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->ready(); }));
        return R;
    };

    auto maybe_R = steps();

    // 2. And then, if an exception E was thrown:

    // 1. If attribute’s type is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    // 2. Otherwise, end these steps and allow the exception to propagate.
    auto R = maybe_R.release_value();

    // 4. Return the result of converting R to a JavaScript value of the type attribute is declared as.
    return GC::Ref { as<JS::Promise>(*R->promise()) };
}

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

    auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {
        // 1. Let idlObject be null.
        [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));
        auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->finished(); }));
        return R;
    };

    auto maybe_R = steps();

    // 2. And then, if an exception E was thrown:

    // 1. If attribute’s type is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    // 2. Otherwise, end these steps and allow the exception to propagate.
    auto R = maybe_R.release_value();

    // 4. Return the result of converting R to a JavaScript value of the type attribute is declared as.
    return GC::Ref { as<JS::Promise>(*R->promise()) };
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::onfinish_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::onfinish_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->onfinish(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(R->callback);
    }();
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::oncancel_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::oncancel_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->oncancel(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(R->callback);
    }();
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::onremove_getter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::onremove_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->onremove(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(R->callback);
    }();
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::id_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::id_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]] Animations::Animation* 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<String> {
        return TRY(WebIDL::to_string(vm, V));
    }(); }));

        // 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_id(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(AnimationPrototype::effect_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::effect_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]] Animations::Animation* 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<GC::Ptr<Animations::AnimationEffect>> {
        GC::Ptr<Animations::AnimationEffect> value;

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<Animations::AnimationEffect>> {
        if (auto impl = V.as_if<Animations::AnimationEffect>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "AnimationEffect");
    }());
        }
        return 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_effect(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(AnimationPrototype::timeline_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::timeline_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]] Animations::Animation* 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<GC::Ptr<Animations::AnimationTimeline>> {
        GC::Ptr<Animations::AnimationTimeline> value;

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<Animations::AnimationTimeline>> {
        if (auto impl = V.as_if<Animations::AnimationTimeline>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "AnimationTimeline");
    }());
        }
        return 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_timeline_for_bindings(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(AnimationPrototype::start_time_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::start_time_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]] Animations::Animation* 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<Variant<double, GC::Ref<CSS::CSSNumericValue>, Empty>> {
        Variant<double, GC::Ref<CSS::CSSNumericValue>, Empty> value;

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<Variant<double, GC::Ref<CSS::CSSNumericValue>>> {

        if (V.is_object()) {
            [[maybe_unused]] auto& object = V.as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<CSS::CSSNumericValue>(object))
                    return Variant<double, GC::Ref<CSS::CSSNumericValue>> { GC::Ref { *result } };
            }
        }

        if (V.is_number()) {
            auto startTime_number = TRY([&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(V.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "startTime");
        return x;
    }());
            return Variant<double, GC::Ref<CSS::CSSNumericValue>> { startTime_number };
        }

        auto startTime_number_fallback = TRY([&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(V.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "startTime");
        return x;
    }());
        return Variant<double, GC::Ref<CSS::CSSNumericValue>> { startTime_number_fallback };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }());
        }
        return 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_start_time_for_bindings(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(AnimationPrototype::current_time_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::current_time_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]] Animations::Animation* 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<Variant<double, GC::Ref<CSS::CSSNumericValue>, Empty>> {
        Variant<double, GC::Ref<CSS::CSSNumericValue>, Empty> value;

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<Variant<double, GC::Ref<CSS::CSSNumericValue>>> {

        if (V.is_object()) {
            [[maybe_unused]] auto& object = V.as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<CSS::CSSNumericValue>(object))
                    return Variant<double, GC::Ref<CSS::CSSNumericValue>> { GC::Ref { *result } };
            }
        }

        if (V.is_number()) {
            auto currentTime_number = TRY([&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(V.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "currentTime");
        return x;
    }());
            return Variant<double, GC::Ref<CSS::CSSNumericValue>> { currentTime_number };
        }

        auto currentTime_number_fallback = TRY([&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(V.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "currentTime");
        return x;
    }());
        return Variant<double, GC::Ref<CSS::CSSNumericValue>> { currentTime_number_fallback };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }());
        }
        return 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_current_time_for_bindings(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(AnimationPrototype::playback_rate_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::playback_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]] Animations::Animation* 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<double> {
        auto x = TRY(V.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "playbackRate");
        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_playback_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(AnimationPrototype::onfinish_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::onfinish_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]] Animations::Animation* 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<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;
        if (V.is_object()) {

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {

        return vm.heap().allocate<WebIDL::CallbackType>(V.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        }
        return 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_onfinish(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(AnimationPrototype::oncancel_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::oncancel_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]] Animations::Animation* 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<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;
        if (V.is_object()) {

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {

        return vm.heap().allocate<WebIDL::CallbackType>(V.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        }
        return 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_oncancel(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(AnimationPrototype::onremove_setter)
{
    WebIDL::log_trace(vm, "AnimationPrototype::onremove_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]] Animations::Animation* 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<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;
        if (V.is_object()) {

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {

        return vm.heap().allocate<WebIDL::CallbackType>(V.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        }
        return 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_onremove(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(AnimationPrototype::cancel)
{
    WebIDL::log_trace(vm, "AnimationPrototype::cancel");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Animations::Animation* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::finish)
{
    WebIDL::log_trace(vm, "AnimationPrototype::finish");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Animations::Animation* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::play)
{
    WebIDL::log_trace(vm, "AnimationPrototype::play");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Animations::Animation* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::pause)
{
    WebIDL::log_trace(vm, "AnimationPrototype::pause");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Animations::Animation* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::update_playback_rate)
{
    WebIDL::log_trace(vm, "AnimationPrototype::update_playback_rate");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Animations::Animation* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto playback_rate = 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, "playbackRate");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->update_playback_rate(playback_rate); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::reverse)
{
    WebIDL::log_trace(vm, "AnimationPrototype::reverse");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Animations::Animation* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(AnimationPrototype::persist)
{
    WebIDL::log_trace(vm, "AnimationPrototype::persist");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Animations::Animation* idl_object = TRY(impl_from(vm));

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

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<AnimationPlayState> convert_to_idl_value_for_animation_play_state(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 == "idle"sv)
        return AnimationPlayState::Idle;
    if (value_as_string == "running"sv)
        return AnimationPlayState::Running;
    if (value_as_string == "paused"sv)
        return AnimationPlayState::Paused;
    if (value_as_string == "finished"sv)
        return AnimationPlayState::Finished;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "AnimationPlayState");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(AnimationPlayState 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 AnimationPlayState::Idle:
        return "idle"_utf16;
    case AnimationPlayState::Running:
        return "running"_utf16;
    case AnimationPlayState::Paused:
        return "paused"_utf16;
    case AnimationPlayState::Finished:
        return "finished"_utf16;
    }
    VERIFY_NOT_REACHED();
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<AnimationReplaceState> convert_to_idl_value_for_animation_replace_state(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 == "active"sv)
        return AnimationReplaceState::Active;
    if (value_as_string == "removed"sv)
        return AnimationReplaceState::Removed;
    if (value_as_string == "persisted"sv)
        return AnimationReplaceState::Persisted;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "AnimationReplaceState");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(AnimationReplaceState 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 AnimationReplaceState::Active:
        return "active"_utf16;
    case AnimationReplaceState::Removed:
        return "removed"_utf16;
    case AnimationReplaceState::Persisted:
        return "persisted"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
