#include <AK/String.h>
#include <AK/TypeCasts.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/Object.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/EventTarget.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/Performance.h>
#include <LibWeb/Bindings/PerformanceMark.h>
#include <LibWeb/Bindings/PerformanceMeasure.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/Performance.h>
#include <LibWeb/NavigationTiming/PerformanceNavigation.h>
#include <LibWeb/NavigationTiming/PerformanceTiming.h>
#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
#include <LibWeb/UserTiming/PerformanceMark.h>
#include <LibWeb/UserTiming/PerformanceMeasure.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

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

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

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

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

    object.set_prototype(GC::Ref { ensure_web_prototype<EventTargetPrototype>(realm, "EventTarget"_fly_string) });

    auto time_origin_id = "timeOrigin"_utf16_fly_string;
    auto native_time_origin_getter = JS::NativeFunction::create(realm, time_origin_getter, 0, time_origin_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_time_origin_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto time_origin_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(time_origin_id, native_time_origin_getter, native_time_origin_setter, time_origin_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 onresourcetimingbufferfull_id = "onresourcetimingbufferfull"_utf16_fly_string;
    auto native_onresourcetimingbufferfull_getter = JS::NativeFunction::create(realm, onresourcetimingbufferfull_getter, 0, onresourcetimingbufferfull_id, &realm, "get"sv);
    auto native_onresourcetimingbufferfull_setter = JS::NativeFunction::create(realm, onresourcetimingbufferfull_setter, 1, onresourcetimingbufferfull_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto onresourcetimingbufferfull_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(onresourcetimingbufferfull_id, native_onresourcetimingbufferfull_getter, native_onresourcetimingbufferfull_setter, onresourcetimingbufferfull_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.
    if (is<HTML::Window>(realm.global_object())) {
        auto timing_id = "timing"_utf16_fly_string;
        auto native_timing_getter = JS::NativeFunction::create(realm, timing_getter, 0, timing_id, &realm, "get"sv);
        GC::Ptr<JS::NativeFunction> native_timing_setter;
    
        // 4. Let configurable be false if attr is unforgeable and true otherwise.
        auto timing_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(timing_id, native_timing_getter, native_timing_setter, timing_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.
        }
    if (is<HTML::Window>(realm.global_object())) {
        auto navigation_id = "navigation"_utf16_fly_string;
        auto native_navigation_getter = JS::NativeFunction::create(realm, navigation_getter, 0, navigation_id, &realm, "get"sv);
        GC::Ptr<JS::NativeFunction> native_navigation_setter;
    
        // 4. Let configurable be false if attr is unforgeable and true otherwise.
        auto navigation_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(navigation_id, native_navigation_getter, native_navigation_setter, navigation_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, "now"_utf16_fly_string, now, 0, default_attributes);

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

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

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

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

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

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

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

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

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

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

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<HighResolutionTime::Performance*> 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(PerformancePrototype::time_origin_getter)
{
    WebIDL::log_trace(vm, "PerformancePrototype::time_origin_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->time_origin(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::onresourcetimingbufferfull_getter)
{
    WebIDL::log_trace(vm, "PerformancePrototype::onresourcetimingbufferfull_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->onresourcetimingbufferfull(); }));

    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(PerformancePrototype::timing_getter)
{
    WebIDL::log_trace(vm, "PerformancePrototype::timing_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->timing(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::navigation_getter)
{
    WebIDL::log_trace(vm, "PerformancePrototype::navigation_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->navigation(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::onresourcetimingbufferfull_setter)
{
    WebIDL::log_trace(vm, "PerformancePrototype::onresourcetimingbufferfull_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]] HighResolutionTime::Performance* 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_onresourcetimingbufferfull(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(PerformancePrototype::now)
{
    WebIDL::log_trace(vm, "PerformancePrototype::now");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::to_json)
{
    WebIDL::log_trace(vm, "PerformancePrototype::to_json");
    auto& realm = *vm.current_realm();

    [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));

    // 4. Let result be OrdinaryObjectCreate(%Object.prototype%).
    auto result = JS::Object::create(realm, realm.intrinsics().object_prototype());

    // 5. For each key → value of map:
    auto time_origin_0_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->time_origin(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto time_origin_0_key = "timeOrigin"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto time_origin_0_value_js = JS::Value(time_origin_0_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(time_origin_0_key, time_origin_0_value_js));
    if (is<HTML::Window>(realm.global_object())) {
        auto timing_1_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->timing(); }));
    
        // 1. Let k be key converted to a JavaScript value.
        auto timing_1_key = "timing"_utf16_fly_string;
    
        // 2. Let v be value converted to a JavaScript value.
        auto timing_1_value_js = JS::Value(timing_1_value);
    
        // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
        MUST(result->create_data_property(timing_1_key, timing_1_value_js));
        }
    if (is<HTML::Window>(realm.global_object())) {
        auto navigation_2_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->navigation(); }));
    
        // 1. Let k be key converted to a JavaScript value.
        auto navigation_2_key = "navigation"_utf16_fly_string;
    
        // 2. Let v be value converted to a JavaScript value.
        auto navigation_2_value_js = JS::Value(navigation_2_value);
    
        // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
        MUST(result->create_data_property(navigation_2_key, navigation_2_value_js));
        }

    // 6. Return result.
    return result;
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::mark)
{
    WebIDL::log_trace(vm, "PerformancePrototype::mark");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

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

    auto arg1 = vm.argument(1);
    PerformanceMarkOptions mark_options = PerformanceMarkOptions {};
    if (!arg1.is_undefined())
        mark_options = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_performance_mark_options(vm, arg1); }));

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

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::clear_marks)
{
    WebIDL::log_trace(vm, "PerformancePrototype::clear_marks");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

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

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::measure)
{
    WebIDL::log_trace(vm, "PerformancePrototype::measure");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

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

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

        if (arg1.is_nullish()) {
            return Variant<String, PerformanceMeasureOptions> { TRY(convert_to_idl_value_for_performance_measure_options(vm, arg1)) };
        }

        if (arg1.is_object()) {
            [[maybe_unused]] auto& object = arg1.as_object();
            return Variant<String, PerformanceMeasureOptions> { TRY(convert_to_idl_value_for_performance_measure_options(vm, arg1)) };
        }

        auto startOrMeasureOptions_string = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }());
        return Variant<String, PerformanceMeasureOptions> { startOrMeasureOptions_string };

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

    auto arg2 = vm.argument(2);
    Optional<String> end_mark {};
    if (!arg2.is_undefined())
        end_mark = 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->measure(measure_name, start_or_measure_options, end_mark); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::clear_measures)
{
    WebIDL::log_trace(vm, "PerformancePrototype::clear_measures");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

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

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::clear_resource_timings)
{
    WebIDL::log_trace(vm, "PerformancePrototype::clear_resource_timings");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::set_resource_timing_buffer_size)
{
    WebIDL::log_trace(vm, "PerformancePrototype::set_resource_timing_buffer_size");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto max_size = 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->set_resource_timing_buffer_size(max_size); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::get_entries)
{
    WebIDL::log_trace(vm, "PerformancePrototype::get_entries");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_entries(); }));
    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;
    }();
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::get_entries_by_type)
{
    WebIDL::log_trace(vm, "PerformancePrototype::get_entries_by_type");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_entries_by_type(type); }));
    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;
    }();
}

JS_DEFINE_NATIVE_FUNCTION(PerformancePrototype::get_entries_by_name)
{
    WebIDL::log_trace(vm, "PerformancePrototype::get_entries_by_name");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HighResolutionTime::Performance* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto name = 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> type {};
    if (!arg1.is_undefined())
        type = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_entries_by_name(name, type); }));
    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;
    }();
}

} // namespace Web::Bindings
