#include <AK/String.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/Selection.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/Range.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/Selection/Selection.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

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

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

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

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

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

    auto anchor_node_id = "anchorNode"_utf16_fly_string;
    auto native_anchor_node_getter = JS::NativeFunction::create(realm, anchor_node_getter, 0, anchor_node_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_anchor_node_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto anchor_node_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(anchor_node_id, native_anchor_node_getter, native_anchor_node_setter, anchor_node_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 anchor_offset_id = "anchorOffset"_utf16_fly_string;
    auto native_anchor_offset_getter = JS::NativeFunction::create(realm, anchor_offset_getter, 0, anchor_offset_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_anchor_offset_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto anchor_offset_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(anchor_offset_id, native_anchor_offset_getter, native_anchor_offset_setter, anchor_offset_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 focus_node_id = "focusNode"_utf16_fly_string;
    auto native_focus_node_getter = JS::NativeFunction::create(realm, focus_node_getter, 0, focus_node_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_focus_node_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto focus_node_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(focus_node_id, native_focus_node_getter, native_focus_node_setter, focus_node_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 focus_offset_id = "focusOffset"_utf16_fly_string;
    auto native_focus_offset_getter = JS::NativeFunction::create(realm, focus_offset_getter, 0, focus_offset_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_focus_offset_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto focus_offset_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(focus_offset_id, native_focus_offset_getter, native_focus_offset_setter, focus_offset_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 is_collapsed_id = "isCollapsed"_utf16_fly_string;
    auto native_is_collapsed_getter = JS::NativeFunction::create(realm, is_collapsed_getter, 0, is_collapsed_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_is_collapsed_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto is_collapsed_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(is_collapsed_id, native_is_collapsed_getter, native_is_collapsed_setter, is_collapsed_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 range_count_id = "rangeCount"_utf16_fly_string;
    auto native_range_count_getter = JS::NativeFunction::create(realm, range_count_getter, 0, range_count_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_range_count_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto range_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(range_count_id, native_range_count_getter, native_range_count_setter, range_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.
    auto type_id = "type"_utf16_fly_string;
    auto native_type_getter = JS::NativeFunction::create(realm, type_getter, 0, type_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_type_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto type_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(type_id, native_type_getter, native_type_setter, type_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 direction_id = "direction"_utf16_fly_string;
    auto native_direction_getter = JS::NativeFunction::create(realm, direction_getter, 0, direction_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_direction_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto direction_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(direction_id, native_direction_getter, native_direction_setter, direction_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, "getRangeAt"_utf16_fly_string, get_range_at, 1, default_attributes);

    object.define_native_function(realm, "addRange"_utf16_fly_string, add_range, 1, default_attributes);

    object.define_native_function(realm, "removeRange"_utf16_fly_string, remove_range, 1, default_attributes);

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

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

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

    object.define_native_function(realm, "setPosition"_utf16_fly_string, set_position, 1, default_attributes);

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

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

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

    object.define_native_function(realm, "setBaseAndExtent"_utf16_fly_string, set_base_and_extent, 4, default_attributes);

    object.define_native_function(realm, "selectAllChildren"_utf16_fly_string, select_all_children, 1, default_attributes);

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

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

    object.define_native_function(realm, "containsNode"_utf16_fly_string, contains_node, 1, default_attributes);

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


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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<Selection::Selection*> 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(SelectionPrototype::anchor_node_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::anchor_node_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->anchor_node(); }));

    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(SelectionPrototype::anchor_offset_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::anchor_offset_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->anchor_offset(); }));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::focus_node_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::focus_node_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->focus_node(); }));

    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(SelectionPrototype::focus_offset_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::focus_offset_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->focus_offset(); }));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::is_collapsed_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::is_collapsed_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->is_collapsed(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::range_count_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::range_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->range_count(); }));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::type_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::type_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->type(); }));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::direction_getter)
{
    WebIDL::log_trace(vm, "SelectionPrototype::direction_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->direction(); }));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::get_range_at)
{
    WebIDL::log_trace(vm, "SelectionPrototype::get_range_at");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

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

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::add_range)
{
    WebIDL::log_trace(vm, "SelectionPrototype::add_range");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto range = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::Range>> {
        if (auto impl = arg0.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->add_range(range); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::remove_range)
{
    WebIDL::log_trace(vm, "SelectionPrototype::remove_range");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto range = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::Range>> {
        if (auto impl = arg0.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->remove_range(range); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::remove_all_ranges)
{
    WebIDL::log_trace(vm, "SelectionPrototype::remove_all_ranges");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::empty)
{
    WebIDL::log_trace(vm, "SelectionPrototype::empty");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

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

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

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

        if (!arg0.is_nullish()) {

            value = TRY([&]() -> 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");
    }());
        }
        return value;
    }(); }));

    auto arg1 = vm.argument(1);
    WebIDL::UnsignedLong offset = 0;
    if (!arg1.is_undefined())
        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->collapse(node, offset); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::set_position)
{
    WebIDL::log_trace(vm, "SelectionPrototype::set_position");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

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

        if (!arg0.is_nullish()) {

            value = TRY([&]() -> 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");
    }());
        }
        return value;
    }(); }));

    auto arg1 = vm.argument(1);
    WebIDL::UnsignedLong offset = 0;
    if (!arg1.is_undefined())
        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_position(node, offset); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::collapse_to_start)
{
    WebIDL::log_trace(vm, "SelectionPrototype::collapse_to_start");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::extend)
{
    WebIDL::log_trace(vm, "SelectionPrototype::extend");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

    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);
    WebIDL::UnsignedLong offset = 0;
    if (!arg1.is_undefined())
        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->extend(node, offset); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::set_base_and_extent)
{
    WebIDL::log_trace(vm, "SelectionPrototype::set_base_and_extent");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto anchor_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 anchor_offset = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

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

    auto arg3 = vm.argument(3);
    auto focus_offset = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg3, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_base_and_extent(anchor_node, anchor_offset, focus_node, focus_offset); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::select_all_children)
{
    WebIDL::log_trace(vm, "SelectionPrototype::select_all_children");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

    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_all_children(node); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::modify)
{
    WebIDL::log_trace(vm, "SelectionPrototype::modify");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

    auto arg1 = vm.argument(1);
    Optional<String> direction {};
    if (!arg1.is_undefined())
        direction = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }(); }));

    auto arg2 = vm.argument(2);
    Optional<String> granularity {};
    if (!arg2.is_undefined())
        granularity = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg2));
    }(); }));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::delete_from_document)
{
    WebIDL::log_trace(vm, "SelectionPrototype::delete_from_document");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Selection::Selection* idl_object = TRY(impl_from(vm));

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

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

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

    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);
    bool allow_partial_containment = false;
    if (!arg1.is_undefined())
        allow_partial_containment = TRY(throw_dom_exception_if_needed(vm, [&] { return arg1.to_boolean(); }));

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

JS_DEFINE_NATIVE_FUNCTION(SelectionPrototype::to_string)
{
    WebIDL::log_trace(vm, "SelectionPrototype::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
