#include <AK/String.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/Event.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/NavigateEvent.h>
#include <LibWeb/Bindings/NavigationType.h>
#include <LibWeb/DOM/AbortSignal.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/HTML/NavigateEvent.h>
#include <LibWeb/HTML/NavigationDestination.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/XHR/FormData.h>

namespace Web::Bindings {

void NavigateEventConstructor::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<EventPrototype>(realm, "Event"_fly_string));
    object.define_direct_property(vm.names.length, JS::Value(2), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "NavigateEvent"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<NavigateEventPrototype>(realm, "NavigateEvent"_fly_string), 0);
}

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

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

    // 3.2. Let prototype be ? Get(newTarget, "prototype").
    auto prototype = TRY(new_target.get(vm.names.prototype));

    // 3.3. If Type(prototype) is not Object, then:
    if (!prototype.is_object()) {
        // 1. Let targetRealm be ? GetFunctionRealm(newTarget).
        auto* target_realm = TRY(JS::get_function_realm(vm, new_target));

        // 2. Set prototype to the interface prototype object for interface in targetRealm.
        VERIFY(target_realm);
        prototype = &Bindings::ensure_web_prototype<NavigateEventPrototype>(*target_realm, "NavigateEvent"_fly_string);
    }

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

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

    auto arg1 = vm.argument(1);
    auto event_init_dict = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_navigate_event_init(vm, arg1); }));

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return HTML::NavigateEvent::construct_impl(realm, type, event_init_dict); }));

    // 7. Set instance.[[Prototype]] to prototype.
    VERIFY(prototype.is_object());
    impl->set_prototype(&prototype.as_object());

    // FIXME: Steps 8...11. of the "internally create a new object implementing the interface NavigateEvent" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within HTML::NavigateEvent::construct_impl().

    return *impl;
}

void NavigateEventPrototype::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<EventPrototype>(realm, "Event"_fly_string) });

    auto navigation_type_id = "navigationType"_utf16_fly_string;
    auto native_navigation_type_getter = JS::NativeFunction::create(realm, navigation_type_getter, 0, navigation_type_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_navigation_type_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto navigation_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(navigation_type_id, native_navigation_type_getter, native_navigation_type_setter, navigation_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 destination_id = "destination"_utf16_fly_string;
    auto native_destination_getter = JS::NativeFunction::create(realm, destination_getter, 0, destination_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_destination_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto destination_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(destination_id, native_destination_getter, native_destination_setter, destination_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 can_intercept_id = "canIntercept"_utf16_fly_string;
    auto native_can_intercept_getter = JS::NativeFunction::create(realm, can_intercept_getter, 0, can_intercept_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_can_intercept_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto can_intercept_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(can_intercept_id, native_can_intercept_getter, native_can_intercept_setter, can_intercept_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 user_initiated_id = "userInitiated"_utf16_fly_string;
    auto native_user_initiated_getter = JS::NativeFunction::create(realm, user_initiated_getter, 0, user_initiated_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_user_initiated_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto user_initiated_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(user_initiated_id, native_user_initiated_getter, native_user_initiated_setter, user_initiated_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 hash_change_id = "hashChange"_utf16_fly_string;
    auto native_hash_change_getter = JS::NativeFunction::create(realm, hash_change_getter, 0, hash_change_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_hash_change_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto hash_change_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(hash_change_id, native_hash_change_getter, native_hash_change_setter, hash_change_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 signal_id = "signal"_utf16_fly_string;
    auto native_signal_getter = JS::NativeFunction::create(realm, signal_getter, 0, signal_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_signal_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto signal_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(signal_id, native_signal_getter, native_signal_setter, signal_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 form_data_id = "formData"_utf16_fly_string;
    auto native_form_data_getter = JS::NativeFunction::create(realm, form_data_getter, 0, form_data_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_form_data_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto form_data_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(form_data_id, native_form_data_getter, native_form_data_setter, form_data_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 download_request_id = "downloadRequest"_utf16_fly_string;
    auto native_download_request_getter = JS::NativeFunction::create(realm, download_request_getter, 0, download_request_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_download_request_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto download_request_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(download_request_id, native_download_request_getter, native_download_request_setter, download_request_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 info_id = "info"_utf16_fly_string;
    auto native_info_getter = JS::NativeFunction::create(realm, info_getter, 0, info_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_info_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto info_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(info_id, native_info_getter, native_info_setter, info_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 has_ua_visual_transition_id = "hasUAVisualTransition"_utf16_fly_string;
    auto native_has_ua_visual_transition_getter = JS::NativeFunction::create(realm, has_ua_visual_transition_getter, 0, has_ua_visual_transition_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_has_ua_visual_transition_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto has_ua_visual_transition_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(has_ua_visual_transition_id, native_has_ua_visual_transition_getter, native_has_ua_visual_transition_setter, has_ua_visual_transition_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 source_element_id = "sourceElement"_utf16_fly_string;
    auto native_source_element_getter = JS::NativeFunction::create(realm, source_element_getter, 0, source_element_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_source_element_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto source_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(source_element_id, native_source_element_getter, native_source_element_setter, source_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, "intercept"_utf16_fly_string, intercept, 0, default_attributes);

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

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<HTML::NavigateEvent*> 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(NavigateEventPrototype::navigation_type_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::navigation_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->navigation_type(); }));

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

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::destination_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::destination_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->destination(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::can_intercept_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::can_intercept_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->can_intercept(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::user_initiated_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::user_initiated_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->user_initiated(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::hash_change_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::hash_change_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->hash_change(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::signal_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::signal_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->signal(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::form_data_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::form_data_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->form_data(); }));

    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(NavigateEventPrototype::download_request_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::download_request_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->download_request(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R.has_value())
            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(WebIDL::primitive_string_from_string(vm, R.value()));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::info_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::info_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->info(); }));

    return R;
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::has_ua_visual_transition_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::has_ua_visual_transition_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->has_ua_visual_transition(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::source_element_getter)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::source_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->source_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(NavigateEventPrototype::intercept)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::intercept");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HTML::NavigateEvent* idl_object = TRY(impl_from(vm));

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

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

JS_DEFINE_NATIVE_FUNCTION(NavigateEventPrototype::scroll)
{
    WebIDL::log_trace(vm, "NavigateEventPrototype::scroll");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HTML::NavigateEvent* idl_object = TRY(impl_from(vm));

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

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<NavigationFocusReset> convert_to_idl_value_for_navigation_focus_reset(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 == "after-transition"sv)
        return NavigationFocusReset::AfterTransition;
    if (value_as_string == "manual"sv)
        return NavigationFocusReset::Manual;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "NavigationFocusReset");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(NavigationFocusReset 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 NavigationFocusReset::AfterTransition:
        return "after-transition"_utf16;
    case NavigationFocusReset::Manual:
        return "manual"_utf16;
    }
    VERIFY_NOT_REACHED();
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<NavigationScrollBehavior> convert_to_idl_value_for_navigation_scroll_behavior(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 == "after-transition"sv)
        return NavigationScrollBehavior::AfterTransition;
    if (value_as_string == "manual"sv)
        return NavigationScrollBehavior::Manual;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "NavigationScrollBehavior");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(NavigationScrollBehavior 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 NavigationScrollBehavior::AfterTransition:
        return "after-transition"_utf16;
    case NavigationScrollBehavior::Manual:
        return "manual"_utf16;
    }
    VERIFY_NOT_REACHED();
}

// https://webidl.spec.whatwg.org/#es-dictionary
JS::ThrowCompletionOr<NavigateEventInit> convert_to_idl_value_for_navigate_event_init(JS::VM& vm, JS::Value js_dict)
{
    // 1. If jsDict is not an Object and jsDict is neither undefined nor null, then throw a TypeError.
    if (!js_dict.is_object() && !js_dict.is_nullish())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "NavigateEventInit");

    // 2. Let idlDict be an empty ordered map, representing a dictionary of type D.
    // 3. Let dictionaries be a list consisting of D and all of D’s inherited dictionaries, in order from least to most derived.
    // 4. For each dictionary dictionary in dictionaries, in order:
    // NB: We defer construction until the return initializer because some members may not be default-constructible. Inherited dictionaries are represented by the generated C++ struct inheritance.

    // 5. Return idlDict.
    return NavigateEventInit {
        TRY(convert_to_idl_value_for_event_init(vm, js_dict)),
        TRY([&]() -> JS::ThrowCompletionOr<bool> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("canIntercept"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_boolean(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = false;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<HTML::NavigationDestination>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("destination"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<HTML::NavigationDestination>> {
        if (auto impl = js_member_value.as_if<HTML::NavigationDestination>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "NavigationDestination");
    }(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 6. Otherwise, if jsMemberValue is undefined and member is required, then throw a TypeError.
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::MissingRequiredProperty, "destination");
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<Optional<String>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("downloadRequest"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<String>> {
        Optional<String> value;

        if (!js_member_value.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, js_member_value));
    }());
        }
        return value;
    }(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = OptionalNone {};

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<XHR::FormData>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("formData"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<XHR::FormData>> {
        GC::Ptr<XHR::FormData> value;

        if (!js_member_value.is_nullish()) {

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

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = nullptr;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<bool> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("hasUAVisualTransition"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_boolean(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = false;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<bool> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("hashChange"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_boolean(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = false;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<Optional<JS::Value>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("info"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value; }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 7. Otherwise, jsMemberValue is undefined and the member is optional.
            return OptionalNone {};
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<NavigationType> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("navigationType"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_navigation_type(vm, js_member_value); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = NavigationType::Push;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::AbortSignal>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("signal"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::AbortSignal>> {
        if (auto impl = js_member_value.as_if<DOM::AbortSignal>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "AbortSignal");
    }(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 6. Otherwise, if jsMemberValue is undefined and member is required, then throw a TypeError.
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::MissingRequiredProperty, "signal");
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<DOM::Element>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("sourceElement"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<DOM::Element>> {
        GC::Ptr<DOM::Element> value;

        if (!js_member_value.is_nullish()) {

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

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = nullptr;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<bool> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("userInitiated"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_boolean(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = false;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
    };
}

// https://webidl.spec.whatwg.org/#es-dictionary
JS::ThrowCompletionOr<NavigationInterceptOptions> convert_to_idl_value_for_navigation_intercept_options(JS::VM& vm, JS::Value js_dict)
{
    // 1. If jsDict is not an Object and jsDict is neither undefined nor null, then throw a TypeError.
    if (!js_dict.is_object() && !js_dict.is_nullish())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "NavigationInterceptOptions");

    // 2. Let idlDict be an empty ordered map, representing a dictionary of type D.
    // 3. Let dictionaries be a list consisting of D and all of D’s inherited dictionaries, in order from least to most derived.
    // 4. For each dictionary dictionary in dictionaries, in order:
    // NB: We defer construction until the return initializer because some members may not be default-constructible. Inherited dictionaries are represented by the generated C++ struct inheritance.

    // 5. Return idlDict.
    return NavigationInterceptOptions {
        .focus_reset = TRY([&]() -> JS::ThrowCompletionOr<Optional<NavigationFocusReset>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("focusReset"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_navigation_focus_reset(vm, js_member_value); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 7. Otherwise, jsMemberValue is undefined and the member is optional.
            return OptionalNone {};
        }()),
        .handler = TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("handler"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {

        if (!js_member_value.is_function())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, js_member_value);

        return vm.heap().allocate<WebIDL::CallbackType>(js_member_value.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::Yes);
    }(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 7. Otherwise, jsMemberValue is undefined and the member is optional.
            return nullptr;
        }()),
        .scroll = TRY([&]() -> JS::ThrowCompletionOr<Optional<NavigationScrollBehavior>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("scroll"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_navigation_scroll_behavior(vm, js_member_value); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 7. Otherwise, jsMemberValue is undefined and the member is optional.
            return OptionalNone {};
        }()),
    };
}

} // namespace Web::Bindings
