#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Animations/Animation.h>
#include <LibWeb/Bindings/DocumentFragment.h>
#include <LibWeb/Bindings/Element.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/Bindings/ShadowRoot.h>
#include <LibWeb/CSS/StyleSheetList.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/TrustedTypes/TrustedHTML.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

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

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

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

    auto mode_id = "mode"_utf16_fly_string;
    auto native_mode_getter = JS::NativeFunction::create(realm, mode_getter, 0, mode_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_mode_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto mode_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(mode_id, native_mode_getter, native_mode_setter, mode_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 delegates_focus_id = "delegatesFocus"_utf16_fly_string;
    auto native_delegates_focus_getter = JS::NativeFunction::create(realm, delegates_focus_getter, 0, delegates_focus_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_delegates_focus_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto delegates_focus_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(delegates_focus_id, native_delegates_focus_getter, native_delegates_focus_setter, delegates_focus_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 slot_assignment_id = "slotAssignment"_utf16_fly_string;
    auto native_slot_assignment_getter = JS::NativeFunction::create(realm, slot_assignment_getter, 0, slot_assignment_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_slot_assignment_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto slot_assignment_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(slot_assignment_id, native_slot_assignment_getter, native_slot_assignment_setter, slot_assignment_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 clonable_id = "clonable"_utf16_fly_string;
    auto native_clonable_getter = JS::NativeFunction::create(realm, clonable_getter, 0, clonable_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_clonable_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto clonable_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(clonable_id, native_clonable_getter, native_clonable_setter, clonable_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 serializable_id = "serializable"_utf16_fly_string;
    auto native_serializable_getter = JS::NativeFunction::create(realm, serializable_getter, 0, serializable_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_serializable_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto serializable_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(serializable_id, native_serializable_getter, native_serializable_setter, serializable_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 host_id = "host"_utf16_fly_string;
    auto native_host_getter = JS::NativeFunction::create(realm, host_getter, 0, host_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_host_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto host_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(host_id, native_host_getter, native_host_setter, host_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 onslotchange_id = "onslotchange"_utf16_fly_string;
    auto native_onslotchange_getter = JS::NativeFunction::create(realm, onslotchange_getter, 0, onslotchange_id, &realm, "get"sv);
    auto native_onslotchange_setter = JS::NativeFunction::create(realm, onslotchange_setter, 1, onslotchange_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto onslotchange_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(onslotchange_id, native_onslotchange_getter, native_onslotchange_setter, onslotchange_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 inner_html_id = "innerHTML"_utf16_fly_string;
    auto native_inner_html_getter = JS::NativeFunction::create(realm, inner_html_getter, 0, inner_html_id, &realm, "get"sv);
    auto native_inner_html_setter = JS::NativeFunction::create(realm, inner_html_setter, 1, inner_html_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto inner_html_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(inner_html_id, native_inner_html_getter, native_inner_html_setter, inner_html_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 custom_element_registry_id = "customElementRegistry"_utf16_fly_string;
    auto native_custom_element_registry_getter = JS::NativeFunction::create(realm, custom_element_registry_getter, 0, custom_element_registry_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_custom_element_registry_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto custom_element_registry_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(custom_element_registry_id, native_custom_element_registry_getter, native_custom_element_registry_setter, custom_element_registry_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 active_element_id = "activeElement"_utf16_fly_string;
    auto native_active_element_getter = JS::NativeFunction::create(realm, active_element_getter, 0, active_element_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_active_element_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto active_element_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(active_element_id, native_active_element_getter, native_active_element_setter, active_element_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 style_sheets_id = "styleSheets"_utf16_fly_string;
    auto native_style_sheets_getter = JS::NativeFunction::create(realm, style_sheets_getter, 0, style_sheets_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_style_sheets_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto style_sheets_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(style_sheets_id, native_style_sheets_getter, native_style_sheets_setter, style_sheets_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 adopted_style_sheets_id = "adoptedStyleSheets"_utf16_fly_string;
    auto native_adopted_style_sheets_getter = JS::NativeFunction::create(realm, adopted_style_sheets_getter, 0, adopted_style_sheets_id, &realm, "get"sv);
    auto native_adopted_style_sheets_setter = JS::NativeFunction::create(realm, adopted_style_sheets_setter, 1, adopted_style_sheets_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto adopted_style_sheets_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(adopted_style_sheets_id, native_adopted_style_sheets_getter, native_adopted_style_sheets_setter, adopted_style_sheets_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 fullscreen_element_id = "fullscreenElement"_utf16_fly_string;
    auto native_fullscreen_element_getter = JS::NativeFunction::create(realm, fullscreen_element_getter, 0, fullscreen_element_id, &realm, "get"sv);
    auto native_fullscreen_element_setter = JS::NativeFunction::create(realm, fullscreen_element_setter, 1, fullscreen_element_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto fullscreen_element_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(fullscreen_element_id, native_fullscreen_element_getter, native_fullscreen_element_setter, fullscreen_element_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, "setHTMLUnsafe"_utf16_fly_string, set_html_unsafe, 1, default_attributes);

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

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

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::ShadowRoot*> 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(ShadowRootPrototype::mode_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::mode_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->mode(); }));

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

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::delegates_focus_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::delegates_focus_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->delegates_focus(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::slot_assignment_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::slot_assignment_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->slot_assignment(); }));

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

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::clonable_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::clonable_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->clonable(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::serializable_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::serializable_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->serializable(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::host_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::host_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->host(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::onslotchange_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::onslotchange_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->onslotchange(); }));

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

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

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::inner_html_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::inner_html_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->inner_html(); }));

    return R.visit(
        [&](GC::Ref<TrustedTypes::TrustedHTML> const& visited_union_value0) -> JS::Value
        {
            return JS::Value(visited_union_value0);
        },
        [&](Utf16String const& visited_union_value1) -> JS::Value
        {
            return WebIDL::primitive_string_from_string(vm, visited_union_value1);
        }
    );
}

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::custom_element_registry_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::custom_element_registry_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->custom_element_registry(); }));

    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(ShadowRootPrototype::active_element_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::active_element_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->active_element(); }));

    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(ShadowRootPrototype::style_sheets_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::style_sheets_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->style_sheets_for_bindings(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::adopted_style_sheets_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::adopted_style_sheets_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->adopted_style_sheets(); }));

    return R;
}

JS_DEFINE_NATIVE_FUNCTION(ShadowRootPrototype::fullscreen_element_getter)
{
    WebIDL::log_trace(vm, "ShadowRootPrototype::fullscreen_element_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->fullscreen_element_for_bindings(); }));

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

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

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

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

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

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

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

    // 5. If attribute is a regular attribute:

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

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

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

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

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;
        if (V.is_object()) {

        if (!V.is_nullish()) {

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

        return vm.heap().allocate<WebIDL::CallbackType>(V.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        }
        return value;
    }(); }));

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

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

        return JS::js_undefined();
    };

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

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

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

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

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

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

    // 5. If attribute is a regular attribute:

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

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

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

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

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<TrustedTypes::TrustedHTML>, Utf16String>> {

        if (V.is_object()) {
            [[maybe_unused]] auto& object = V.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 innerHTML_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        Utf16String string;
        if (!V.is_null())
            string = TRY(WebIDL::to_utf16_string(vm, V));
        return string;
    }());
        return Variant<GC::Ref<TrustedTypes::TrustedHTML>, Utf16String> { innerHTML_string };

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

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

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

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return 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();
    }());
}

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

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

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

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

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

    // 5. If attribute is a regular attribute:

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

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

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

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

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

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

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

        return JS::js_undefined();
    };

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

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

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

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

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

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

    // 5. If attribute is a regular attribute:

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

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

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

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

    // 7. If attribute is declared with a [LegacyLenientSetter] extended attribute, then return undefined.
    return JS::js_undefined();
}

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

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

    auto arg0 = vm.argument(0);
    auto html = 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 html_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, arg0));
    }());
        return Variant<GC::Ref<TrustedTypes::TrustedHTML>, Utf16String> { html_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->set_html_unsafe(html); });
    };

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

    auto arg0 = vm.argument(0);
    GetHTMLOptions options = GetHTMLOptions {};
    if (!arg0.is_undefined())
        options = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_get_html_options(vm, arg0); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_html(options); }));
    return WebIDL::primitive_string_from_string(vm, R);
}

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_animations(); }));
    return [&]() -> JS::Value {
        // An IDL sequence<T> value S is converted to a JavaScript value as follows:
        // 1. Let n be the length of S.
        auto sequence_length = R.size();

        // 2. Let A be a new Array object created as if by the expression [].
        auto sequence_array = MUST(JS::Array::create(realm, sequence_length));

        // 3. Initialize i to be 0.
        // 4. While i < n:
        for (size_t sequence_index = 0; sequence_index < sequence_length; ++sequence_index) {
            // 1. Let V be the value in S at index i.
            auto& sequence_element = R.at(sequence_index);

            // 2. Let E be the result of converting V to a JavaScript value.
            JS::Value js_sequence_element = JS::Value(sequence_element);

            // 3. Let P be the result of calling ! ToString(i).
            // 4. Perform ! CreateDataPropertyOrThrow(A, P, E).
            MUST(sequence_array->create_data_property(JS::PropertyKey { sequence_index }, js_sequence_element));

            // 5. Set i to i + 1.
        }

        // 5. Return A.
        return sequence_array;
    }();
}

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

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

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

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

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

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

} // namespace Web::Bindings
