#include <AK/Array.h>
#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/TypeCasts.h>
#include <AK/Utf16FlyString.h>
#include <AK/Utf16String.h>
#include <LibGC/Ptr.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/HTMLElement.h>
#include <LibWeb/Bindings/HTMLTrackElement.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ElementFactory.h>
#include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
#include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
#include <LibWeb/HTML/HTMLTrackElement.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/HTML/TextTrack.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Infra/Strings.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void HTMLTrackElementConstructor::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<HTMLElementPrototype>(realm, "HTMLElement"_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, "HTMLTrackElement"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<HTMLTrackElementPrototype>(realm, "HTMLTrackElement"_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("NONE"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(0)), 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("LOADING"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(1)), 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("LOADED"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(2)), 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("ERROR"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(3)), JS::Attribute::Enumerable);
}

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

    // 1. If NewTarget is equal to the active function object, then throw a TypeError.
    if (&new_target == vm.active_function_object())
        return vm.throw_completion<JS::TypeError>("Cannot directly construct an HTML element, it must be inherited"_utf16);

    // 2. Let registry be null.
    GC::Ptr<HTML::CustomElementRegistry> registry;

    // 3. If the surrounding agent's active custom element constructor map[NewTarget] exists:
    auto& surrounding_agent = HTML::relevant_similar_origin_window_agent(window);
    if (auto registry_for_constructor = surrounding_agent.active_custom_element_constructor_map.get(GC::Ref { new_target }); registry_for_constructor.has_value() && !registry_for_constructor->is_null()) {
        // 1. Set registry to the surrounding agent's active custom element constructor map[NewTarget].
        registry = registry_for_constructor.value();

        // 2. Remove the surrounding agent's active custom element constructor map[NewTarget].
        surrounding_agent.active_custom_element_constructor_map.remove(GC::Ref { new_target });
    }
    // 4. Otherwise, set registry to current global object's associated Document's custom element registry.
    else {
        registry = window.associated_document().custom_element_registry();
    }

    // 5. Let definition be the item in registry's custom element definition set with constructor equal to NewTarget.
    //    If there is no such item, then throw a TypeError.
    auto definition = registry->get_definition_from_new_target(new_target);
    if (!definition)
        return vm.throw_completion<JS::TypeError>("There is no custom element definition assigned to the given constructor"_utf16);

    // 6. Let isValue be null.
    Optional<Utf16FlyString> is_value;

    // 7. If definition's local name is equal to definition's name (i.e., definition is for an autonomous custom element):
    if (definition->local_name() == definition->name()) {
        // 1. If the active function object is not HTMLElement, then throw a TypeError.
        return vm.throw_completion<JS::TypeError>("Autonomous custom elements can only inherit from HTMLElement"_utf16);
    }
    // 8. Otherwise (i.e., if definition is for a customized built-in element):
    else {
        // 1. Let valid local names be the list of local names for elements defined in this specification or in other applicable specifications that use the active function object as their element interface.
        static auto const& valid_local_names = *new auto(MUST(DOM::valid_local_names_for_given_html_element_interface("HTMLTrackElement"sv)));

        // 2. If valid local names does not contain definition's local name, then throw a TypeError.
        if (!valid_local_names.contains_slow(definition->local_name()))
            return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Local name '{}' of customized built-in element is not a valid local name for HTMLTrackElement", definition->local_name()));

        // 3. Set isValue to definition's name.
        is_value = definition->name();
    }

    // 9. If definition's construction stack is empty:
    if (definition->construction_stack().is_empty()) {
        // 1. Let element be the result of internally creating a new object implementing the interface to which the active function object corresponds, given the current Realm Record and NewTarget.
        // 2. Set element's node document to the current global object's associated Document.
        // 3. Set element's namespace to the HTML namespace.
        // 4. Set element's namespace prefix to null.
        // 5. Set element's local name to definition's local name.
        auto element = realm.create<HTML::HTMLTrackElement>(window.associated_document(), DOM::QualifiedName { definition->local_name(), {}, Namespace::HTML });

        // https://webidl.spec.whatwg.org/#internally-create-a-new-object-implementing-the-interface
        TRY(WebIDL::set_prototype_from_new_target<HTMLTrackElementPrototype>(vm, new_target, "HTMLTrackElement"_fly_string, *element));

        // 6. Set element's custom element registry to registry.
        element->set_custom_element_registry(registry);

        // 7. Set element's custom element state to "custom".
        // 8. Set element's custom element definition to definition.
        // 9. Set element's is value to isValue.
        element->setup_custom_element_from_constructor(*definition, is_value);

        // 10. Return element.
        return *element;
    }

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

    // 11. If Type(prototype) is not Object, then:
    if (!prototype.is_object()) {
        // 1. Let realm be ? GetFunctionRealm(NewTarget).
        auto* function_realm = TRY(JS::get_function_realm(vm, new_target));

        // 2. Set prototype to the interface prototype object of realm whose interface is the same as the interface of the active function object.
        VERIFY(function_realm);
        prototype = &Bindings::ensure_web_prototype<HTMLTrackElementPrototype>(*function_realm, "HTMLTrackElement"_fly_string);
    }

    VERIFY(prototype.is_object());

    // 12. Let element be the last entry in definition's construction stack.
    auto& element = definition->construction_stack().last();

    // 13. If element is an already constructed marker, then throw a TypeError.
    if (element.has<HTML::AlreadyConstructedCustomElementMarker>())
        return vm.throw_completion<JS::TypeError>("Custom element has already been constructed"_utf16);

    // 14. Perform ? element.[[SetPrototypeOf]](prototype).
    auto actual_element = element.get<GC::Ref<DOM::Element>>();
    TRY(actual_element->internal_set_prototype_of(&prototype.as_object()));

    // 15. Replace the last entry in definition's construction stack with an already constructed marker.
    definition->construction_stack().last() = HTML::AlreadyConstructedCustomElementMarker {};

    // 16. Return element.
    return *actual_element;
}

void HTMLTrackElementPrototype::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<HTMLElementPrototype>(realm, "HTMLElement"_fly_string) });

    auto kind_id = "kind"_utf16_fly_string;
    auto native_kind_getter = JS::NativeFunction::create(realm, kind_getter, 0, kind_id, &realm, "get"sv);
    auto native_kind_setter = JS::NativeFunction::create(realm, kind_setter, 1, kind_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto kind_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(kind_id, native_kind_getter, native_kind_setter, kind_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 src_id = "src"_utf16_fly_string;
    auto native_src_getter = JS::NativeFunction::create(realm, src_getter, 0, src_id, &realm, "get"sv);
    auto native_src_setter = JS::NativeFunction::create(realm, src_setter, 1, src_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto src_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(src_id, native_src_getter, native_src_setter, src_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 srclang_id = "srclang"_utf16_fly_string;
    auto native_srclang_getter = JS::NativeFunction::create(realm, srclang_getter, 0, srclang_id, &realm, "get"sv);
    auto native_srclang_setter = JS::NativeFunction::create(realm, srclang_setter, 1, srclang_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto srclang_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(srclang_id, native_srclang_getter, native_srclang_setter, srclang_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 label_id = "label"_utf16_fly_string;
    auto native_label_getter = JS::NativeFunction::create(realm, label_getter, 0, label_id, &realm, "get"sv);
    auto native_label_setter = JS::NativeFunction::create(realm, label_setter, 1, label_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto label_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(label_id, native_label_getter, native_label_setter, label_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 default__id = "default"_utf16_fly_string;
    auto native_default__getter = JS::NativeFunction::create(realm, default__getter, 0, default__id, &realm, "get"sv);
    auto native_default__setter = JS::NativeFunction::create(realm, default__setter, 1, default__id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto default__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(default__id, native_default__getter, native_default__setter, default__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 ready_state_id = "readyState"_utf16_fly_string;
    auto native_ready_state_getter = JS::NativeFunction::create(realm, ready_state_getter, 0, ready_state_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_ready_state_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto ready_state_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(ready_state_id, native_ready_state_getter, native_ready_state_setter, ready_state_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 track_id = "track"_utf16_fly_string;
    auto native_track_getter = JS::NativeFunction::create(realm, track_getter, 0, track_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_track_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto track_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(track_id, native_track_getter, native_track_setter, track_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.

    // 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("NONE"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(0)), 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("LOADING"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(1)), 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("LOADED"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(2)), 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("ERROR"_utf16_fly_string, JS::Value(static_cast<WebIDL::UnsignedShort>(3)), JS::Attribute::Enumerable);
    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "HTMLTrackElement"_utf16), JS::Attribute::Configurable);
}

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<HTML::HTMLTrackElement*> 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(HTMLTrackElementPrototype::kind_getter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::kind_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

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


    // If a reflected IDL attribute is an enumerated attribute:
    // 1. Let contentAttributeValue be the result of running this's get the content attribute.
    auto content_attribute_value = idl_object->attribute("kind"_utf16_fly_string);

    // 2. If contentAttributeValue is null, then set contentAttributeValue to the missing value default.
    auto R = content_attribute_value.value_or("subtitles"_utf16);
    auto did_set_to_missing_value = false;
    if (!content_attribute_value.has_value())
        did_set_to_missing_value = true;

    // 3. If contentAttributeValue is an ASCII case-insensitive match for one of the keywords, then return that keyword's canonical keyword.
    Array valid_values { "subtitles"_utf16, "captions"_utf16, "descriptions"_utf16, "chapters"_utf16, "metadata"_utf16 };
    auto has_keyword = false;
    for (auto const& value : valid_values) {
        if (value.equals_ignoring_ascii_case(R)) {
            has_keyword = true;
            R = value;
            break;
        }
    }

    // 4. If contentAttributeValue is not a keyword and was not set to the missing value default, return the invalid value default.
    if (!has_keyword && !did_set_to_missing_value)
        R = "metadata"_utf16;

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

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

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


    // If a reflected IDL attribute has the type USVString:
    // 1. Let element be the result of running this's get the element.
    // 2. Let contentAttributeValue be the result of running this's get the content attribute.
    auto content_attribute_value = idl_object->attribute("src"_utf16_fly_string);

    // 3. Let attributeDefinition be the attribute definition of element's content attribute whose namespace is null and local name is the reflected content attribute name.

    // 4. If attributeDefinition indicates it contains a URL:
    Utf16String R;
    if (content_attribute_value.has_value()) {
        // 2. Let urlString be the result of encoding-parsing-and-serializing a URL given contentAttributeValue, relative to element's node document.
        auto url_string = idl_object->document().encoding_parse_and_serialize_url(*content_attribute_value);

        // 3. If urlString is not failure, then return urlString.
        if (url_string.has_value())
            R = Utf16String::from_utf8(url_string.release_value());
        else
            R = MUST(Infra::convert_to_scalar_value_string(*content_attribute_value));
    }

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

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

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


    // If a reflected IDL attribute has the type DOMString:
    // 1. Let element be the result of running this's get the element.
    // 2. Let contentAttributeValue be the result of running this's get the content attribute.
    // 5. If contentAttributeValue is null, then return the empty string.
    // 6. Return contentAttributeValue.
    auto R = idl_object->get_attribute_value("srclang"_utf16_fly_string);

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

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

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


    // If a reflected IDL attribute has the type DOMString:
    // 1. Let element be the result of running this's get the element.
    // 2. Let contentAttributeValue be the result of running this's get the content attribute.
    // 5. If contentAttributeValue is null, then return the empty string.
    // 6. Return contentAttributeValue.
    auto R = idl_object->get_attribute_value("label"_utf16_fly_string);

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

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

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


    // If a reflected IDL attribute has the type boolean:
    // 1. Let contentAttributeValue be the result of running this's get the content attribute.
    // 2. If contentAttributeValue is null, then return false.
    auto R = idl_object->has_attribute("default"_utf16_fly_string);

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(HTMLTrackElementPrototype::ready_state_getter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::ready_state_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->ready_state(); }));

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

JS_DEFINE_NATIVE_FUNCTION(HTMLTrackElementPrototype::track_getter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::track_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->track(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(HTMLTrackElementPrototype::kind_setter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::kind_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]] HTML::HTMLTrackElement* 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<String> {
        return TRY(WebIDL::to_string(vm, V));
    }(); }));

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

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

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
}

JS_DEFINE_NATIVE_FUNCTION(HTMLTrackElementPrototype::src_setter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::src_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]] HTML::HTMLTrackElement* 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<String> {
        return TRY(WebIDL::to_usv_string(vm, V));
    }(); }));

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

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

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
}

JS_DEFINE_NATIVE_FUNCTION(HTMLTrackElementPrototype::srclang_setter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::srclang_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]] HTML::HTMLTrackElement* 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<String> {
        return TRY(WebIDL::to_string(vm, V));
    }(); }));

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

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

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
}

JS_DEFINE_NATIVE_FUNCTION(HTMLTrackElementPrototype::label_setter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::label_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]] HTML::HTMLTrackElement* 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<String> {
        return TRY(WebIDL::to_string(vm, V));
    }(); }));

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

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

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
}

JS_DEFINE_NATIVE_FUNCTION(HTMLTrackElementPrototype::default__setter)
{
    WebIDL::log_trace(vm, "HTMLTrackElementPrototype::default__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]] HTML::HTMLTrackElement* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

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

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

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

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

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

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            if (!idl_value)
        idl_object->remove_attribute("default"_utf16_fly_string);
    else
        idl_object->set_attribute_value("default"_utf16_fly_string, Utf16String {});
    return {};
        }();

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

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<TrackKindAttribute> convert_to_idl_value_for_track_kind_attribute(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 == "subtitles"sv)
        return TrackKindAttribute::Subtitles;
    if (value_as_string == "captions"sv)
        return TrackKindAttribute::Captions;
    if (value_as_string == "descriptions"sv)
        return TrackKindAttribute::Descriptions;
    if (value_as_string == "chapters"sv)
        return TrackKindAttribute::Chapters;
    if (value_as_string == "metadata"sv)
        return TrackKindAttribute::Metadata;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "TrackKindAttribute");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(TrackKindAttribute 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 TrackKindAttribute::Subtitles:
        return "subtitles"_utf16;
    case TrackKindAttribute::Captions:
        return "captions"_utf16;
    case TrackKindAttribute::Descriptions:
        return "descriptions"_utf16;
    case TrackKindAttribute::Chapters:
        return "chapters"_utf16;
    case TrackKindAttribute::Metadata:
        return "metadata"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
