#include <AK/String.h>
#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <LibGC/ConservativeVector.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/DocumentFragment.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/Node.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/DOM/DocumentFragment.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/HTMLCollection.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/NodeList.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void DocumentFragmentConstructor::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<NodePrototype>(realm, "Node"_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, "DocumentFragment"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<DocumentFragmentPrototype>(realm, "DocumentFragment"_fly_string), 0);
}

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

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

    // 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<DocumentFragmentPrototype>(*target_realm, "DocumentFragment"_fly_string);
    }

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return DOM::DocumentFragment::construct_impl(realm); }));

    // 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 DocumentFragment" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within DOM::DocumentFragment::construct_impl().

    return *impl;
}

void DocumentFragmentPrototype::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<NodePrototype>(realm, "Node"_fly_string) });

    auto children_id = "children"_utf16_fly_string;
    auto native_children_getter = JS::NativeFunction::create(realm, children_getter, 0, children_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_children_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto children_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(children_id, native_children_getter, native_children_setter, children_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 first_element_child_id = "firstElementChild"_utf16_fly_string;
    auto native_first_element_child_getter = JS::NativeFunction::create(realm, first_element_child_getter, 0, first_element_child_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_first_element_child_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto first_element_child_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(first_element_child_id, native_first_element_child_getter, native_first_element_child_setter, first_element_child_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 last_element_child_id = "lastElementChild"_utf16_fly_string;
    auto native_last_element_child_getter = JS::NativeFunction::create(realm, last_element_child_getter, 0, last_element_child_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_last_element_child_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto last_element_child_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(last_element_child_id, native_last_element_child_getter, native_last_element_child_setter, last_element_child_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 child_element_count_id = "childElementCount"_utf16_fly_string;
    auto native_child_element_count_getter = JS::NativeFunction::create(realm, child_element_count_getter, 0, child_element_count_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_child_element_count_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto child_element_count_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(child_element_count_id, native_child_element_count_getter, native_child_element_count_setter, child_element_count_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, "getElementById"_utf16_fly_string, get_element_by_id, 1, default_attributes);

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

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

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

    object.define_native_function(realm, "moveBefore"_utf16_fly_string, move_before, 2, default_attributes);

    object.define_native_function(realm, "querySelector"_utf16_fly_string, query_selector, 1, default_attributes);

    object.define_native_function(realm, "querySelectorAll"_utf16_fly_string, query_selector_all, 1, default_attributes);

    auto unscopable_object = JS::Object::create(realm, nullptr);
    MUST(unscopable_object->create_data_property("prepend"_utf16_fly_string, JS::Value(true)));
    MUST(unscopable_object->create_data_property("append"_utf16_fly_string, JS::Value(true)));
    MUST(unscopable_object->create_data_property("replaceChildren"_utf16_fly_string, JS::Value(true)));
    object.define_direct_property(vm.well_known_symbol_unscopables(), unscopable_object, JS::Attribute::Configurable);

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

void DocumentFragmentPrototype::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<DOM::DocumentFragment*> impl_from(JS::VM& vm, JS::Value js_value)
{

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

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::DocumentFragment*> 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(DocumentFragmentPrototype::children_getter)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::children_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->children(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(DocumentFragmentPrototype::first_element_child_getter)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::first_element_child_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->first_element_child(); }));

    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(DocumentFragmentPrototype::last_element_child_getter)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::last_element_child_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->last_element_child(); }));

    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(DocumentFragmentPrototype::child_element_count_getter)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::child_element_count_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->child_element_count(); }));

    return JS::Value(static_cast<WebIDL::UnsignedLong>(R));
}

JS_DEFINE_NATIVE_FUNCTION(DocumentFragmentPrototype::get_element_by_id)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::get_element_by_id");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::DocumentFragment* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto id = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, arg0));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_element_by_id(id); }));
    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(DocumentFragmentPrototype::prepend)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::prepend");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::DocumentFragment* idl_object = TRY(impl_from(vm));

    GC::ConservativeVector<Variant<GC::Ref<DOM::Node>, Utf16String>> nodes;
    if (vm.argument_count() > 0) {
        nodes.ensure_capacity(vm.argument_count() - 0);
        for (size_t i = 0; i < vm.argument_count(); ++i) {
            auto argument = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Node>, Utf16String>> {

        if (vm.argument(i).is_object()) {
            [[maybe_unused]] auto& object = vm.argument(i).as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<DOM::Node>(object))
                    return Variant<GC::Ref<DOM::Node>, Utf16String> { GC::Ref { *result } };
            }
        }

        auto nodes_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, vm.argument(i)));
    }());
        return Variant<GC::Ref<DOM::Node>, Utf16String> { nodes_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));
            nodes.unchecked_append(move(argument));
        }
    }

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->prepend(nodes); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(DocumentFragmentPrototype::append)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::append");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::DocumentFragment* idl_object = TRY(impl_from(vm));

    GC::ConservativeVector<Variant<GC::Ref<DOM::Node>, Utf16String>> nodes;
    if (vm.argument_count() > 0) {
        nodes.ensure_capacity(vm.argument_count() - 0);
        for (size_t i = 0; i < vm.argument_count(); ++i) {
            auto argument = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Node>, Utf16String>> {

        if (vm.argument(i).is_object()) {
            [[maybe_unused]] auto& object = vm.argument(i).as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<DOM::Node>(object))
                    return Variant<GC::Ref<DOM::Node>, Utf16String> { GC::Ref { *result } };
            }
        }

        auto nodes_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, vm.argument(i)));
    }());
        return Variant<GC::Ref<DOM::Node>, Utf16String> { nodes_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));
            nodes.unchecked_append(move(argument));
        }
    }

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->append(nodes); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(DocumentFragmentPrototype::replace_children)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::replace_children");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::DocumentFragment* idl_object = TRY(impl_from(vm));

    GC::ConservativeVector<Variant<GC::Ref<DOM::Node>, Utf16String>> nodes;
    if (vm.argument_count() > 0) {
        nodes.ensure_capacity(vm.argument_count() - 0);
        for (size_t i = 0; i < vm.argument_count(); ++i) {
            auto argument = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Node>, Utf16String>> {

        if (vm.argument(i).is_object()) {
            [[maybe_unused]] auto& object = vm.argument(i).as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<DOM::Node>(object))
                    return Variant<GC::Ref<DOM::Node>, Utf16String> { GC::Ref { *result } };
            }
        }

        auto nodes_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, vm.argument(i)));
    }());
        return Variant<GC::Ref<DOM::Node>, Utf16String> { nodes_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));
            nodes.unchecked_append(move(argument));
        }
    }

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->replace_children(nodes); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(DocumentFragmentPrototype::move_before)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::move_before");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::DocumentFragment* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto node = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::Node>> {
        if (auto impl = arg0.as_if<DOM::Node>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Node");
    }(); }));

    auto arg1 = vm.argument(1);
    auto child = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<DOM::Node>> {
        GC::Ptr<DOM::Node> value;

        if (!arg1.is_nullish()) {

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

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->move_before(node, child); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(DocumentFragmentPrototype::query_selector)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::query_selector");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::DocumentFragment* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto selectors = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->query_selector(selectors); }));
    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(DocumentFragmentPrototype::query_selector_all)
{
    WebIDL::log_trace(vm, "DocumentFragmentPrototype::query_selector_all");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::DocumentFragment* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto selectors = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

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

} // namespace Web::Bindings
