#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/PropertyDescriptor.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/AbstractRange.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/Bindings/Range.h>
#include <LibWeb/DOM/DocumentFragment.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/Range.h>
#include <LibWeb/Geometry/DOMRect.h>
#include <LibWeb/Geometry/DOMRectList.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/TrustedTypes/TrustedHTML.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void RangeConstructor::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<AbstractRangePrototype>(realm, "AbstractRange"_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, "Range"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<RangePrototype>(realm, "Range"_fly_string), 0);

    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("START_TO_START"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(0)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("START_TO_END"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(1)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("END_TO_END"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(2)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("END_TO_START"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(3)), JS::Attribute::Enumerable);
}

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

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

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

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return DOM::Range::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 Range" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within DOM::Range::construct_impl().

    return *impl;
}

void RangePrototype::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<AbstractRangePrototype>(realm, "AbstractRange"_fly_string) });

    auto common_ancestor_container_id = "commonAncestorContainer"_utf16_fly_string;
    auto native_common_ancestor_container_getter = JS::NativeFunction::create(realm, common_ancestor_container_getter, 0, common_ancestor_container_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_common_ancestor_container_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto common_ancestor_container_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(common_ancestor_container_id, native_common_ancestor_container_getter, native_common_ancestor_container_setter, common_ancestor_container_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, "setStart"_utf16_fly_string, set_start, 2, default_attributes);

    object.define_native_function(realm, "setEnd"_utf16_fly_string, set_end, 2, default_attributes);

    object.define_native_function(realm, "setStartBefore"_utf16_fly_string, set_start_before, 1, default_attributes);

    object.define_native_function(realm, "setStartAfter"_utf16_fly_string, set_start_after, 1, default_attributes);

    object.define_native_function(realm, "setEndBefore"_utf16_fly_string, set_end_before, 1, default_attributes);

    object.define_native_function(realm, "setEndAfter"_utf16_fly_string, set_end_after, 1, default_attributes);

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

    object.define_native_function(realm, "selectNode"_utf16_fly_string, select_node, 1, default_attributes);

    object.define_native_function(realm, "selectNodeContents"_utf16_fly_string, select_node_contents, 1, default_attributes);

    object.define_native_function(realm, "compareBoundaryPoints"_utf16_fly_string, compare_boundary_points, 2, default_attributes);

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

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

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

    object.define_native_function(realm, "insertNode"_utf16_fly_string, insert_node, 1, default_attributes);

    object.define_native_function(realm, "surroundContents"_utf16_fly_string, surround_contents, 1, default_attributes);

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

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

    object.define_native_function(realm, "isPointInRange"_utf16_fly_string, is_point_in_range, 2, default_attributes);

    object.define_native_function(realm, "comparePoint"_utf16_fly_string, compare_point, 2, default_attributes);

    object.define_native_function(realm, "intersectsNode"_utf16_fly_string, intersects_node, 1, default_attributes);

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

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

    object.define_native_function(realm, "createContextualFragment"_utf16_fly_string, create_contextual_fragment, 1, default_attributes);

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



    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("START_TO_START"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(0)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("START_TO_END"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(1)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("END_TO_END"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(2)), JS::Attribute::Enumerable);
    // 1. FIXME: If const is not exposed in realm, then continue.
    // 2. Let value be the result of converting const’s IDL value to a JavaScript value.
    // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false, [[Value]]: value}.
    // 4. Let id be const’s identifier.
    // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_property("END_TO_START"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(3)), JS::Attribute::Enumerable);
    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "Range"_utf16), JS::Attribute::Configurable);
}

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::Range*> 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(RangePrototype::common_ancestor_container_getter)
{
    WebIDL::log_trace(vm, "RangePrototype::common_ancestor_container_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->common_ancestor_container(); }));

    return JS::Value(R);
}

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

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "setStart", "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 offset = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

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

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

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "setEnd", "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 offset = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

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

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

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

    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");
    }(); }));

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

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

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

    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");
    }(); }));

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

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

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

    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");
    }(); }));

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

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

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

    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");
    }(); }));

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

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

    auto arg0 = vm.argument(0);
    bool to_start = false;
    if (!arg0.is_undefined())
        to_start = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0.to_boolean(); }));

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

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

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

    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");
    }(); }));

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

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

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

    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");
    }(); }));

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

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

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

    auto arg0 = vm.argument(0);
    auto how = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedShort>(vm, arg0, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->compare_boundary_points(how, source_range); }));
    return JS::Value(static_cast<WebIDL::Short>(R));
}

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

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

    [[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(RangePrototype::extract_contents)
{
    WebIDL::log_trace(vm, "RangePrototype::extract_contents");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::Range* idl_object = TRY(impl_from(vm));

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

    [[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::Value(R);
}

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

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

    [[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::Value(R);
}

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

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

    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 original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->insert_node(node); });
    };

    [[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(RangePrototype::surround_contents)
{
    WebIDL::log_trace(vm, "RangePrototype::surround_contents");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::Range* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto new_parent = 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 original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->surround_contents(new_parent); });
    };

    [[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(RangePrototype::clone_range)
{
    WebIDL::log_trace(vm, "RangePrototype::clone_range");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::Range* idl_object = TRY(impl_from(vm));

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

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

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

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

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "isPointInRange", "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 offset = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

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

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

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "comparePoint", "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 offset = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->compare_point(node, offset); }));
    return JS::Value(static_cast<WebIDL::Short>(R));
}

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

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

    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");
    }(); }));

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

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

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

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

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

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

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

    auto arg0 = vm.argument(0);
    auto string = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<TrustedTypes::TrustedHTML>, Utf16String>> {

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

            if (is<PlatformObject>(object)) {

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

        auto string_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, arg0));
    }());
        return Variant<GC::Ref<TrustedTypes::TrustedHTML>, Utf16String> { string_string };

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

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

    [[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::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(RangePrototype::to_string)
{
    WebIDL::log_trace(vm, "RangePrototype::to_string");
    auto* idl_object = TRY(impl_from(vm));
    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->to_string(); }));
    return WebIDL::primitive_string_from_string(vm, R);
}

} // namespace Web::Bindings
