#include <AK/String.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/PropertyDescriptor.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/KeyboardEvent.h>
#include <LibWeb/Bindings/UIEvent.h>
#include <LibWeb/HTML/WindowProxy.h>
#include <LibWeb/UIEvents/KeyboardEvent.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void KeyboardEventConstructor::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<UIEventPrototype>(realm, "UIEvent"_fly_string));
    object.define_direct_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "KeyboardEvent"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<KeyboardEventPrototype>(realm, "KeyboardEvent"_fly_string), 0);

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

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

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

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

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

    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);
    KeyboardEventInit event_init_dict = KeyboardEventInit {};
    if (!arg1.is_undefined())
        event_init_dict = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_keyboard_event_init(vm, arg1); }));

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

    return *impl;
}

void KeyboardEventPrototype::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<UIEventPrototype>(realm, "UIEvent"_fly_string) });

    auto key_id = "key"_utf16_fly_string;
    auto native_key_getter = JS::NativeFunction::create(realm, key_getter, 0, key_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_key_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto key_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(key_id, native_key_getter, native_key_setter, key_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 code_id = "code"_utf16_fly_string;
    auto native_code_getter = JS::NativeFunction::create(realm, code_getter, 0, code_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_code_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto code_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(code_id, native_code_getter, native_code_setter, code_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 location_id = "location"_utf16_fly_string;
    auto native_location_getter = JS::NativeFunction::create(realm, location_getter, 0, location_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_location_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto location_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(location_id, native_location_getter, native_location_setter, location_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 ctrl_key_id = "ctrlKey"_utf16_fly_string;
    auto native_ctrl_key_getter = JS::NativeFunction::create(realm, ctrl_key_getter, 0, ctrl_key_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_ctrl_key_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto ctrl_key_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(ctrl_key_id, native_ctrl_key_getter, native_ctrl_key_setter, ctrl_key_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 shift_key_id = "shiftKey"_utf16_fly_string;
    auto native_shift_key_getter = JS::NativeFunction::create(realm, shift_key_getter, 0, shift_key_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_shift_key_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto shift_key_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(shift_key_id, native_shift_key_getter, native_shift_key_setter, shift_key_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 alt_key_id = "altKey"_utf16_fly_string;
    auto native_alt_key_getter = JS::NativeFunction::create(realm, alt_key_getter, 0, alt_key_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_alt_key_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto alt_key_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(alt_key_id, native_alt_key_getter, native_alt_key_setter, alt_key_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 meta_key_id = "metaKey"_utf16_fly_string;
    auto native_meta_key_getter = JS::NativeFunction::create(realm, meta_key_getter, 0, meta_key_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_meta_key_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto meta_key_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(meta_key_id, native_meta_key_getter, native_meta_key_setter, meta_key_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 repeat_id = "repeat"_utf16_fly_string;
    auto native_repeat_getter = JS::NativeFunction::create(realm, repeat_getter, 0, repeat_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_repeat_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto repeat_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(repeat_id, native_repeat_getter, native_repeat_setter, repeat_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto is_composing_id = "isComposing"_utf16_fly_string;
    auto native_is_composing_getter = JS::NativeFunction::create(realm, is_composing_getter, 0, is_composing_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_is_composing_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto is_composing_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(is_composing_id, native_is_composing_getter, native_is_composing_setter, is_composing_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 char_code_id = "charCode"_utf16_fly_string;
    auto native_char_code_getter = JS::NativeFunction::create(realm, char_code_getter, 0, char_code_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_char_code_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto char_code_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(char_code_id, native_char_code_getter, native_char_code_setter, char_code_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 key_code_id = "keyCode"_utf16_fly_string;
    auto native_key_code_getter = JS::NativeFunction::create(realm, key_code_getter, 0, key_code_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_key_code_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto key_code_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(key_code_id, native_key_code_getter, native_key_code_setter, key_code_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, "getModifierState"_utf16_fly_string, get_modifier_state, 1, default_attributes);

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


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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<UIEvents::KeyboardEvent*> 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(KeyboardEventPrototype::key_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::key_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->key(); }));

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

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::code_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::code_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->code(); }));

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

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::location_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::location_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->location(); }));

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

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::ctrl_key_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::ctrl_key_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->ctrl_key(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::shift_key_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::shift_key_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->shift_key(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::alt_key_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::alt_key_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->alt_key(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::meta_key_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::meta_key_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->meta_key(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::repeat_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::repeat_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->repeat(); }));

    return JS::Value(R);
}

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

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->is_composing(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::char_code_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::char_code_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->char_code(); }));

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

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::key_code_getter)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::key_code_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->key_code(); }));

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

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::get_modifier_state)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::get_modifier_state");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] UIEvents::KeyboardEvent* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto key_arg = 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_modifier_state(key_arg); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(KeyboardEventPrototype::init_keyboard_event)
{
    WebIDL::log_trace(vm, "KeyboardEventPrototype::init_keyboard_event");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] UIEvents::KeyboardEvent* idl_object = TRY(impl_from(vm));

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

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

    auto arg1 = vm.argument(1);
    bool bubbles_arg = false;
    if (!arg1.is_undefined())
        bubbles_arg = TRY(throw_dom_exception_if_needed(vm, [&] { return arg1.to_boolean(); }));

    auto arg2 = vm.argument(2);
    bool cancelable_arg = false;
    if (!arg2.is_undefined())
        cancelable_arg = TRY(throw_dom_exception_if_needed(vm, [&] { return arg2.to_boolean(); }));

    auto arg3 = vm.argument(3);
    GC::Ptr<HTML::WindowProxy> view_arg = nullptr;
    if (!arg3.is_undefined())
        view_arg = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<HTML::WindowProxy>> {
        GC::Ptr<HTML::WindowProxy> value;

        if (!arg3.is_nullish()) {

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

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

    auto arg5 = vm.argument(5);
    WebIDL::UnsignedLong location_arg = 0;
    if (!arg5.is_undefined())
        location_arg = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg5, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

    auto arg6 = vm.argument(6);
    bool ctrl_key = false;
    if (!arg6.is_undefined())
        ctrl_key = TRY(throw_dom_exception_if_needed(vm, [&] { return arg6.to_boolean(); }));

    auto arg7 = vm.argument(7);
    bool alt_key = false;
    if (!arg7.is_undefined())
        alt_key = TRY(throw_dom_exception_if_needed(vm, [&] { return arg7.to_boolean(); }));

    auto arg8 = vm.argument(8);
    bool shift_key = false;
    if (!arg8.is_undefined())
        shift_key = TRY(throw_dom_exception_if_needed(vm, [&] { return arg8.to_boolean(); }));

    auto arg9 = vm.argument(9);
    bool meta_key = false;
    if (!arg9.is_undefined())
        meta_key = TRY(throw_dom_exception_if_needed(vm, [&] { return arg9.to_boolean(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->init_keyboard_event(type_arg, bubbles_arg, cancelable_arg, view_arg, key_arg, location_arg, ctrl_key, alt_key, shift_key, meta_key); }));
    return JS::js_undefined();
}

// https://webidl.spec.whatwg.org/#es-dictionary
JS::ThrowCompletionOr<KeyboardEventInit> convert_to_idl_value_for_keyboard_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, "KeyboardEventInit");

    // 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 KeyboardEventInit {
        TRY(convert_to_idl_value_for_event_modifier_init(vm, js_dict)),
        TRY([&]() -> JS::ThrowCompletionOr<WebIDL::UnsignedLong> {
            // 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("charCode"_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 WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, js_member_value, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

                // 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 = 0;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<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("code"_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<String> {
        return TRY(WebIDL::to_string(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 = String {};

            // 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("isComposing"_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<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("key"_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<String> {
        return TRY(WebIDL::to_string(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 = String {};

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<WebIDL::UnsignedLong> {
            // 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("keyCode"_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 WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, js_member_value, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

                // 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 = 0;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        TRY([&]() -> JS::ThrowCompletionOr<WebIDL::UnsignedLong> {
            // 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("location"_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 WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, js_member_value, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

                // 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 = 0;

            // 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("repeat"_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;
        }()),
    };
}

} // namespace Web::Bindings
